over 6 years ago

Property 基本宣告

前一章有提到在 class 與 structure 內設定 property。

class MyClass {
    var p = 0
}

Structures 可以在初始化時同時初始 property。

struct MyStruct {
    var p: Int
}
let s = MyStruct(p:123)

Lazy property

宣告 Lazy 關鍵字的 property 會直到被呼叫到才會初始化,一定要給予初始值。

class MyClass {
    lazy var p = 0
}

運算 property

實際上的功用不是儲存值,而是用來做其他的運算。

class MyClass {
    var value1 = 1
    var value2 = 2
    var computed: Int {
        get {
                return value1 + value2
        }
        set (new){
                value2 = newValue
        }
    }
}

set 中的 new 參數可以省略,直接用預設的 newValue 來操作也可以。
read-only 可以透過不寫 set 來實作,且可以直接省略 get 關鍵字。

class MyClass {
    var readonly: String {
        return "123"
    }
}

Property 觀察

對 property 設定 willSet 與 didSet,在給予值的時候會被呼叫。

class MyClass {
    var p = 0 {
        willSet {
        }
        didSet {
        }
    }
}

Static property

Static 關鍵字可以讓 property 不被侷限於一個實體內,而是所有相同類別的實體共同使用。

class MyClass {
    static var p = 1
}
MyClass.p
← iOS Swift : Classes and Structures iOS Swift : Methods & Subscripts →