Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 252
Daniel Avatar asked Nov 26 '25 20:11

Daniel


2 Answers

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.

like image 98
Antonio Avatar answered Nov 29 '25 16:11

Antonio


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.

like image 35
LuckyStarr Avatar answered Nov 29 '25 16:11

LuckyStarr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!