Property observers willSet and didSet; Property getters and setters

前端 未结 5 1828
孤城傲影
孤城傲影 2020-12-07 17:22

What is the difference between willSet - didSet, and get - set, when working with this inside a property?

From my

5条回答
  •  臣服心动
    2020-12-07 18:22

    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'
    

提交回复
热议问题