本文介绍了swift willSet didSet并在属性中获取set方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在属性中使用此属性时,willSet
-didSet
和get
-set
有什么区别?
What is the difference between willSet
- didSet
, and get
- set
, when working with this inside a property?
从我的角度来看,他们两个都可以为属性设置值.
From my point of view, both of them can set a value for a property. When, and why, should I use willSet
- didSet
, and when get
- set
?
我知道对于willSet
和didSet
,结构看起来像这样:
I know that for willSet
and didSet
, the structure looks like this:
var variable1 : Int = 0 {
didSet {
println (variable1)
}
willSet(newValue) {
..
}
}
var variable2: Int {
get {
return variable2
}
set (newValue){
}
}
推荐答案
-
willSet
在存储该值之前之前被称为. -
didSet
在新值存储后后立即被调用. willSet
is called just before the value is stored.didSet
is called immediately after the new value is stored.
考虑带有输出的示例:
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
它的工作原理类似于前/后条件
it works like pre/post -condition
另一方面,如果要添加例如只读属性,则可以使用get
:
On the other hand, you can use get
if you want to add, for example, a read-only property:
var value : Int {
get {
return 34
}
}
print(value)
value = 2 // error: cannot assign to a get-only property 'value'
这篇关于swift willSet didSet并在属性中获取set方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!