Getter computed property vs. variable that returns a value

1.4k Views Asked by At

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
    }
}
2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

They are identical since both define a read-only computed property. But the former is preferable because it is shorter and more readable than the latter.