我已經爲遵守協議的結構創建了一個全局變量。該變量有一個setter觀察者,每當設置變量時就完成一項任務。由於結構本身遵守協議,我希望變量的類型是協議類型。安裝程序在計算變量訪問計算變量期間調用struct,協議轉換
protocol TestProtocol {
var someInt: Int {get set}
var computedVar: Int {get}
func funcCall() -> Int
}
struct TestStruct: TestProtocol {
var someInt: Int = 1
var computedVar: Int {
return 0
}
func funcCall() -> Int {
return 2
}
}
var testProtocolVar: TestProtocol = TestStruct() {
willSet(newTest) {
print ("*** Setter testProtocolVar called!!!")
}
}
問題是,當我得到一個協議屬性的值是結構中的計算屬性時,變量設置器也被調用。
/***
When a variable is defined and typecast as a protocol, calling a
computed variable on the variable (a class or a struct) the setter
method of the variable will be called (Undesired Behaviour).
***/
print ("\n\n *** Test Protocol Cast Variable *** \n\n")
testProtocolVar
testProtocolVar.someInt
print("Setter has not been called")
testProtocolVar.funcCall()
print("Setter has not been called after function")
testProtocolVar.computedVar
print("Setter has been called when using computed variable")
/*
*** Test Protocol Cast Variable ***
Setter has not been called
Setter has not been called after function
*** Setter testProtocolVar called!!!
Setter has been called when using computed variable
*/
變量是結構類型的類似情況不會觸發setter。
print ("\n\n *** Test Normal Cast Variable *** \n\n")
/***
When a variable is defined and typecast as the struct type, calling a
computed variable on the variable the setter method of the variable
will NOT be called (Desired Behaviour).
***/
var testVar:TestStruct = testProtocolVar as! TestStruct
testVar
testVar.someInt
print("Setter has not been called")
testVar.funcCall()
print("Setter has not been called after function")
testVar.computedVar
print("Setter has not been called when using computed variable")
/*
*** Test Normal Cast Variable ***
Setter has not been called
Setter has not been called after function
Setter has not been called when using computed variable
*/
有沒有人有解釋爲什麼設置觀察員被稱爲?
這似乎是一個迅速的錯誤,除非我失去了一些東西。
我認爲這是一個錯誤。 – courteouselk
同意。對我來說看起來像一個bug。 –