CODEX

Getters and Setters in Swift

Learn how getters and setters work with computed properties in Swift.

Artturi Jalli
CodeX
Published in
2 min readJan 19, 2021

--

Photo by Christopher Gower on Unsplash

You can store properties into classes, structures, and enumerations. Those properties are called stored properties.

In addition to stored properties, we can define properties that aren’t stored anywhere. Instead of directly accessing these properties, they’re computed on demand. These properties are called computed properties.

Computed properties offer getter and setter methods for accessing and changing related properties of the object.

Example—Weight Class

Say we’re dealing with weights and we want to use both kilos and pounds. In code, we’d like to be able to update both kilos and pounds such that both show the correct number.

Let’s implement a Weight class with a computed property to achieve this:

Now you can create Weight objects and update both pounds and kilos without issues:

--

--

Artturi Jalli
CodeX

Check @jalliartturi on YouTube to become a successful blogger. (For collabs, reach me out at: artturi@bloggersgoto.com)