What are 'get' and 'set' in Swift?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Swift, get and set are accessors for computed properties. They define how a property returns a value when read and how it updates underlying data when written, instead of simply storing the value directly the way a stored property does.
Core Sections
Stored Properties Versus Computed Properties
A stored property keeps its value in memory:
By contrast, a computed property calculates its value when accessed:
Here area is not stored separately. Swift runs the get block each time area is read.
What get Does
The getter returns the property's current value. In many cases, a computed property only needs a getter, which makes it read-only.
Because there is no setter, fahrenheit can be read but not assigned directly.
Swift also allows a shorthand form for simple read-only properties:
What set Does
The setter runs when code assigns a new value to the property. It usually updates one or more stored properties behind the scenes.
newValue is the default name for the incoming value assigned to the property.
You can also give it a custom name:
Why This Is Useful
Getters and setters let you expose a convenient API without duplicating data. They are useful when:
- one property is derived from another
- writes need validation or transformation
- you want a public property interface backed by private storage
For example:
This ensures the balance never becomes negative through that property interface.
get and set Versus Property Observers
Swift also has willSet and didSet, but those are different. Property observers react when a stored property changes. get and set define the behavior of a computed property itself.
If you need to calculate or transform values dynamically, use a computed property. If you already have a stored property and only want to observe assignments, use observers instead.
Common Pitfalls
- Trying to treat a computed property like stored memory instead of backing it with other state.
- Writing a setter that assigns to the computed property itself and causes infinite recursion.
- Hiding expensive work inside a getter and then forgetting it runs every time the property is accessed.
- Adding a setter when the property should really be read-only.
- Confusing computed-property accessors with
willSetanddidSetobservers on stored properties.
Summary
- '
getandsetdefine how computed properties are read and written in Swift.' - '
getreturns a value;sethandles assignments throughnewValueor a custom parameter name.' - Computed properties differ from stored properties because they do not keep their own separate value.
- Use accessors to derive values, validate writes, or expose cleaner APIs.
- Avoid recursive setter logic and unnecessary heavy work inside getters.

