Swift 类

从这篇文章,你将学习到如何使用 Swift 的类,具有 Swift 的结构体的能力,而且还有更多,当然其涵盖的内容较多,这里先只讲解大概,更多细节可以查看下面类的能力。
类的能力
定义
定义了类 VideoMode,有一个结构体属性 resolution、布尔属性 interlaced、浮点属性 frameRate 和字符串属性 name。
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
创建实例
创建了类 VideoMode 的实例,其所有属性都是默认值。
let someVideoMode = VideoMode()
访问属性
通过 . 就可以访问属性,当然还可以给属性赋值。
print("The width of someVideoMode is \(someVideoMode.resolution.width)")
someVideoMode.resolution.width = 1280
print("The width of someVideoMode is now \(someVideoMode.resolution.width)")
类是引用类型
引用类型,在赋值或者当作参数传递给函数时,只会传递实例的引用。
let hd = Resolution(width: 1920, height: 1080)
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0
print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
恒等运算符
因为类是引用类型,所以我们需要一个运算符来比较两个常量或变量是否指向同一个类的实例,这就是 === 和 !==。
if tenEighty === alsoTenEighty {
print("same instance")
}
if tenEighty !== alsoTenEighty {
print("not same instance")
}