首页 > 编程语言 > 详细

Swift语言精要 - 属性

时间:2016-04-01 20:40:49      阅读:102      评论:0      收藏:0      [点我收藏+]

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语言精要 - 属性

原文:http://www.cnblogs.com/davidgu/p/5346042.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!