Property observers willSet and didSet; Property getters and setters

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

    @Maxim's answer is for the 1st part of your question.

    As for when to use get and set: when you want a computed property. This:

    var x: Int
    

    creates a stored property, which is automatically backed up by a variable (not directly accessible though). Setting a value to that property is translated in setting the value in the property, and similarly for getting.

    Instead:

    var y = {
        get { return x + 5 }
        set { x = newValue - 5}
    }
    

    will create a computed property, which is not backed up by a variable - instead you have to provide the implementation of the getter and/or setter, usually reading and writing values from another property and more generally as a result of a computation (hence the computed property name)

    Suggested reading: Properties

    Note: your code:

    var variable2: Int {
        get{
            return variable2
        }
        set (newValue){
        }
    }
    

    is wrong because in the get you are trying to return itself, which means calling get recursively. And in fact the compiler will warn you with a message like Attempting to access 'variable2' within its own getter.

提交回复
热议问题