Property observers willSet and didSet; Property getters and setters

前端 未结 5 1837
孤城傲影
孤城傲影 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:07

    get set:

    get set are Computed Properties Which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly

    Additionally you can define Read-Only Computed Properties. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value

    Example get only property-

     var number: Double {
            return .pi*2
        }
    

    willSet didSet:

    willSet didSet are Property Observers

    Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.

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

    Example -

    var score: Int = 0 {
        willSet(newScore) {
            print("willSet  score to \(newScore)")
        }
        didSet {
            print("didSet score to \(oldValue) new score is: \(score)")
        }
    }
    score = 10
    //Output 
    //willSet  score to 10
    //didSet score to 0 new score is: 10
    

    https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

提交回复
热议问题