【发布时间】:2017-08-20 09:49:06
【问题描述】:
我正在阅读有关 swift 中的 willset 和 didset 属性的信息 我开始知道我可以将这些与具有如下初始值的变量一起使用:
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")
}
}
【问题讨论】:
标签: swift properties getter-setter