0 Replies
      Latest reply on Jan 14, 2019 10:57 AM by alvin777
      • Re: What's the Willset & Didset for If There's Get & Set Already?
        Claude31 Level 8 Level 8 (5,775 points)

        WillSet let you do something BEFORE value changes


        didSet, AFTER the value has changed.


        They are not used to set the value. So you still need set to do it.


        When you want to know more on this type of (legitimate) question, go to Swify language book. You will get in depth explanations:


        « If you don’t need to compute the property but still need to provide code that is run before and after setting a new value, use willSet and didSet. The code you provide is run any time the value changes outside of an initializer.  »


        « If you implement a willSet observer, it’s passed the new property value as a constant parameter. You can specify a name for this parameter as part of your willSet implementation. If you don’t write the parameter name and parentheses within your implementation, the parameter is made available with a default parameter name of newValue.


        « Similarly, if you implement a didSet observer, it’s passed a constant parameter containing the old property value. You can name the parameter or use the default parameter name of oldValue. If you assign a value to a property within its own didSet observer, the new value that you assign replaces the one that was just set .


        From: Apple Inc. « The Swift Programming Language (Swift 4). » iBooks.


        S, as conclusion, they are complementary:

        • set and get let you SET and ACCESS the computed properties, but you cannot see what was the previous value
        • willSet and didSet let you OBSERVE when you set the property (even if does not change, up to you to test) and let you see the previous value


        Note: there is no willGet or didGet