swift willSet didSet并在属性中获取set方法(swift willSet didSet and get set methods in a property)

编程入门 行业动态 更新时间:2024-10-28 10:26:19
swift willSet didSet并在属性中获取set方法(swift willSet didSet and get set methods in a property)

在使用var / property之前,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){ } }

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?

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 。 存储新值立即调用didSet 。

考虑你的例子与输出:


var variable1 : Int = 0 { didSet{ println("didSet called") } willSet(newValue){ println("willSet called") } } println("we are going to add 3") variable1 = 3 println("we added 3")

输出:

we are going to add 3 willSet called didSet called we added 3

它的作用就像前/后条件

另一方面,您可以使用get如果要添加例如只读属性:

var value : Int { get { return 34 } } println(value) value = 2 // error: cannot assign to a get-only property 'value'

When and why should I use willSet/didSet

willSet is called just before the value is stored. didSet is called immediately after the new value is stored.

Consider your example with outputs:


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")

Output:

we are going to add 3 willSet called didSet called we added 3

it works like pre/post -condition

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'

更多推荐

本文发布于:2023-08-02 04:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1368504.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并在   属性   方法   willSet   didSet

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!