的內部屬性時,請考慮這樣的代碼只能在協議中定義的屬性會導致編譯錯誤:獲取修改對象
protocol SomeProtocol {
var something: Bool { get set }
}
class SomeProtocolImplementation: SomeProtocol {
var something: Bool = false {
didSet {
print("something changed!")
}
}
}
protocol MyProtocol {
var myProperty: SomeProtocol { get }
}
class MyClass: MyProtocol {
var myProperty: SomeProtocol = SomeProtocolImplementation() {
didSet {
print("myProperty has changed")
}
}
}
var o: MyProtocol = MyClass()
o.myProperty.something = true
此代碼不能用錯誤編譯:
error: cannot assign to property: 'myProperty' is a get-only property
o.myProperty.something = true
~~~~~~~~~~~~ ^
爲什麼?我的屬性是SomeProtocolImplementation類型,它是類類型,所以應該可以使用對myProperty的引用來修改它的內部屬性。
的進一步深入,修改myProperty的定義,使它看起來像後:
var myProperty: SomeProtocol { get set }
奇怪的事情發生了。現在代碼編譯(並不意外),但輸出是:
something changed!
myProperty has changed
所以在這一點SomeProtocolImplementation開始表現得像一個值類型 - modyifing它的內部狀態導致了「didSet」回調myProperty的被觸發。正如SomeProtocolImplementation將結構...
我實際上找到解決方案,但我也想知道發生了什麼事。解決方案是修改SomeProtocol定義爲:
protocol SomeProtocol: class {
var something: Bool { get set }
}
它工作正常,但我想明白爲什麼它的行爲是這樣的。任何人都可以解釋?