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!"
时间: 2024-10-03 05:54:29