在属性内处理此时willSet
-didSet
和get
-之间有什么区别set
?
从我的角度来看,它们两者都可以为属性设置值。什么时候,为什么,我应该使用willSet
- didSet
,什么时候get
- set
?
我知道forwillSet
和didSet
的结构如下:
var variable1 : Int = 0 {
didSet {
println (variable1)
}
willSet(newValue) {
..
}
}
var variable2: Int {
get {
return variable2
}
set (newValue){
}
}
什么时候以及为什么要使用willSet / didSet
willSet
在值存储之前被调用。didSet
新值存储后立即调用。考虑带有输出的示例:
var variable1 : Int = 0 {
didSet{
print("didSet called")
}
willSet(newValue){
print("willSet called")
}
}
print("we are going to add 3")
variable1 = 3
print("we added 3")
输出:
we are going to add 3
willSet called
didSet called
we added 3
它像前/后条件一样工作
另一方面,get
如果要添加例如只读属性,则可以使用:
var value : Int {
get {
return 34
}
}
print(value)
value = 2 // error: cannot assign to a get-only property 'value'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句