3

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
    }
}
Daniel
  • 3,758
  • 3
  • 22
  • 43

2 Answers2

6

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.

Antonio
  • 71,651
  • 11
  • 148
  • 165
  • In case of single-line expressions you may also omit `return` just writing `var computedProperty: Int { something }` starting with Swift 5.1. – Frank Zielen Aug 08 '23 at 21:24
3

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.

LuckyStarr
  • 1,468
  • 2
  • 26
  • 39