jus*_* ME 45 properties ios swift didset
willSet
- didSet
和get
- 之间的区别是什么set
?
从我的角度来看,他们都可以为一个属性设置一个值.何时以及为什么我应该使用willSet
- didSet
,何时get
- set
?
我知道,对于willSet
和didSet
,结构看起来像这样:
var variable1 : Int = 0 {
didSet {
println (variable1)
}
willSet(newValue) {
..
}
}
var variable2: Int {
get {
return variable2
}
set (newValue){
}
}
Run Code Online (Sandbox Code Playgroud)
Max*_*tin 45
何时以及为什么我应该使用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")
Run Code Online (Sandbox Code Playgroud)
输出:
we are going to add 3
willSet called
didSet called
we added 3
Run Code Online (Sandbox Code Playgroud)
它像前/后条件一样工作
另一方面,get
如果要添加,例如,只读属性,则可以使用:
var value : Int {
get {
return 34
}
}
print(value)
value = 2 // error: cannot assign to a get-only property 'value'
Run Code Online (Sandbox Code Playgroud)
Ant*_*nio 23
@Maxim的答案是问题的第1部分.
至于何时使用get
和set
:何时需要计算属性.这个:
var x: Int
Run Code Online (Sandbox Code Playgroud)
创建一个存储属性,该属性由变量自动备份(尽管不能直接访问).设置该属性的值将在设置属性中的值时进行转换,类似于获取.
代替:
var y = {
get { return x + 5 }
set { x = newValue - 5}
}
Run Code Online (Sandbox Code Playgroud)
将创建一个不由变量备份的计算属性 - 而是必须提供getter和/或setter的实现,通常从另一个属性读取和写入值,更通常是计算的结果(因此计算属性名称)
建议阅读:属性
注意:您的代码:
var variable2: Int {
get{
return variable2
}
set (newValue){
}
}
Run Code Online (Sandbox Code Playgroud)
是错的,因为在get
你试图返回自己,这意味着get
递归调用.实际上编译器会用类似的消息警告你Attempting to access 'variable2' within its own getter
.
归档时间: |
|
查看次数: |
43578 次 |
最近记录: |