swiftgettercomputed-values

Getter computed property vs. variable that returns a value


Is there a difference between a getter computed property and variable that returns a value? E.g. is there a difference between the following two variables?

var NUMBER_OF_ELEMENTS1: Int {
    return sampleArray.count
}

var NUMBER_OF_ELEMENTS2: Int {
    get {
        return sampleArray.count
    }
}

Solution

  • A computer property with getter and setter has this form:

    var computedProperty: Int {
        get {
            return something // Implementation can be something more complicated than this
        }
        set {
            something = newValue // Implementation can be something more complicated than this
        }
    }
    

    In some cases a setter is not needed, so the computed property is declared as:

    var computedProperty: Int {
        get {
            return something // Implementation can be something more complicated than this
        }
    }
    

    Note that a computed property must always have a getter - so it's not possible to declare one with a setter only.

    Since it frequently happens that computed properties have a getter only, Swift let us simplify their implementation by omitting the get block, making the code simpler to write and easier to read:

    var computedProperty: Int {
        return something // Implementation can be something more complicated than this
    }
    

    Semantically there's no difference between the 2 versions, so whichever you use, the result is the same.