您的位置:首页 > 移动开发 > Swift

Swift 实例方法&类型方法(九)

2016-03-29 00:12 330 查看
iOS交流群: 498143780 一起学习

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let counter = Counter()
counter.reset()
print(counter.count) // 0
counter.incrementBy(5)
print(counter.count) // 5
counter.increment()
print(counter.count) //

let counter1 = Counter1()
counter1.incrementBy(5, numberOfTimes: 10)
print(counter1.count) // 50

let point = Point()
print(point.isToRightOfX(1)) //
print(point.x)
}


// 'Counter'类定义了三个個实例方法
class Counter {
var count = 0
func incrementBy(amount: Int){
count += amount // count + amount
}
func reset(){
count = 0 // 重置 count = 0
}
func increment(){
self.count++
}
}


// 稍微复杂一点的
class Counter1 {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int){
count += amount * numberOfTimes
}
}


// 下面的例子中,`self`消除方法参数`x`和实例属性`x`之间的歧义
struct Point {
var x = 0.0, y = 0.0
func isToRightOfX(x:  Double) -> Bool{
print(x)           // 1.0
return self.x >= x // self.x = 0 x = 上边赋值1
}
}


/// 第一:struct没有继承的功能,而class是可以继承的,这是面向对象语言的核心能力,class当然会有这个能力。

/// 第二: 体现在内存使用上,struct是通过值传递,而class是通过引用传递的,举个简单的例子window对象一定会选择设计成class的实例,而不应该是struct的,通常我们一定不想在设备中拷贝出多个window对象来,对么?

解释来自:

http://blog.objcc.com/swift-struct-class/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: