Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

swift - Property observers willSet and didSet; Property getters and setters

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){
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...