Getters and Setters in Swift

Getters and Setters in Swift

In Swift, you can store properties inside classes, structures, and enumerations. These properties are known as stored properties. As an example, a Person class could have a property called name.

In addition to stored properties, you can define properties that are not stored anywhere. Instead, they are computed on-demand when accessing them. These properties are called computed properties.

Computed properties offer getter and setter methods to work with.

  • The getter method get() is computes the value when accessing the property.
  • The setter method set() indirectly modifies other related properties.

Let's see what these mean in action.

Example

Say you're dealing with weights. It is important you can work with kilos and pounds smoothly. So you'd like to be able to do at least something like this:

let weight = Weight()

weight.kilograms = 100
print(weight.pounds)

weight.pounds = 315
print(weight.kilograms)

Output:

220.5
142.85715

Let's implement a Weight class that utilizes computed properties to achieve the desired behavior:

class Weight {
    var kilograms: Float = 0.0
    var pounds: Float {
        get {
            return (kilograms * 2.205)
        }
        set(newWeight) {
            kilograms = newWeight / 2.205
        }
    }
}

Now with this simple class, you get the exact behavior you wanted. Let's test it:

let weight = Weight()

weight.kilograms = 100
print(weight.pounds)

weight.pounds = 315
print(weight.kilograms)

Output:

220.5
142.85715

Good. Changing kilos updates pounds and changing pounds updates kilos.

How Does It Work?

Take a look at the implementation of the Weight class above. kilograms is just a variable that is stored in the weight object (a stored property). But pounds is a computed property. It has two jobs:

  1. Convert kilograms to pounds on demand.
  2. Indirectly change kilograms when pounds are updated.

1. Convert Kilograms to Pounds

The weight object doesn't know what it weighs in pounds. When you call weight.pounds the number of pounds gets computed by the getter method:

get {
    return (kilograms * 2.205)
}

2. Update Kilograms When Pounds Change

When you update weight in pounds:

weight.pounds = 315

The setter method gets triggered:

set(newWeight) {
    kilograms = newWeight / 2.205
}

Even though syntactically it looks as if the pounds was updated, you actually updated the kilograms indirectly via pounds with the setter method. The setter method converts the new amount of pounds to kilos and updates the kilograms accordingly.

Conclusion

Computed properties come in handy when we don't need to store a value in the object. Computed properties use getter methods to calculate the property on demand. They also can use setters methods to indirectly modify related properties.

Thanks for reading. I hope you find it useful. Happy coding!