Swift语言精要 - 属性
Posted Master HaKu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift语言精要 - 属性相关的知识,希望对你有一定的参考价值。
1. Stored Property
eg:
var number: Int = 0
2. Computed Property
eg:
var area : Double {
get {
return width * height
}
...
}
完整代码如下:
class Rectangle { var width: Double = 0.0 var height: Double = 0.0 var area : Double { // computed getter get { return width * height } // computed setter set { // Assume equal dimensions (i.e., a square) width = sqrt(newValue) height = sqrt(newValue) } } }
测试代码:
var rect = Rectangle() rect.width = 3.0 rect.height = 4.5 rect.area // = 13.5 rect.area = 9 // width & height now both 3.0
3. Property Observer(属性观察者)
class PropertyObserverExample { var number : Int = 0 { willSet(newNumber) { println("About to change to \(newNumber)") } didSet(oldNumber) { println("Just changed from \(oldNumber) to \(self.number)!") } } }
测试代码如下:
var observer = PropertyObserverExample() observer.number = 4 // prints "About to change to 4", then "Just changed from 0 to 4!"
4. Lazy Property(属性迟绑定)
class SomeExpensiveClass { init(id : Int) { println("Expensive class \(id) created!") } } class LazyPropertyExample { var expensiveClass1 = SomeExpensiveClass(id: 1) lazy var expensiveClass2 = SomeExpensiveClass(id: 2) init() { println("First class created!") } }
测试代码如下:
var lazyExample = LazyPropertyExample() // prints "Expensive class 1 created", then "First class created!" lazyExample.expensiveClass1 // prints nothing, it‘s already created lazyExample.expensiveClass2 // prints "Expensive class 2 created!"
以上是关于Swift语言精要 - 属性的主要内容,如果未能解决你的问题,请参考以下文章