我讀到有關willset並迅速 性能didset我才知道,我可以像下面的變量有初始值使用這些:我們可以使用willset和didset與getter和setter
var property = "name"
{
willSet
{
print("property is about to changed")
}
didSet
{
if property == oldValue
{
print("values are same")
}
else
{
print("value changed")
}
}
}
property = "anothername"
所以我可以使用willget和didset象下面這樣:
var property2:String{
willSet
{
print("value is about to change")
}
didSet
{
print("value is changes")
}
}
它給了我這個錯誤:
non-member observing properties require an initializer
var property2:String{
^
所以任何人都可以給我解釋一下這是怎麼回事,我可以使用getter和setter與willset和didset一起想:
var property2:String{
get{return property2}
set{propert2 = newValue}
willSet
{
print("value is about to change")
}
didSet
{
print("value is changes")
}
}
沒有違法,但可選的替代缺失的初始化是最糟糕的建議。 – vadian