Understand Properties in Swift
Properties associate values with a particular class, structure, or enumeration.
There are two type of properties in Swift:
- Stored: Constant and variable values are stored as part of an instance.
- Computed: A value is calculated rather than store.
Note: Enumerations can only have computed properties.
Join the Swiftable Community to connect with iOS Engineers.
Stored Properties:
Stored properties can be either variable stored properties (with var
keyword) or constant stored properties (with the let
keyword).
A default value for a stored property can be given in definition like
Or values can be set or modified during initialization.
Constant instances Stored Properties:
As structure is value type so when its instance is created as constant then all its properties too can not be modified.
But this is not the case with classes, if a class instance is declared as constant still its properties can be modified because of the class reference type behavior.
Lazy Stored Properties:
A lazy stored property is a property whose initial value is not calculated until the first time it is used. A stored property can be declared as lazy by writing the lazy modifier before its declaration.
Two important things to note:
- A lazy property can never be a constant as a constant property must always have a value before initialization completes.
- There is no guarantee that the lazy property will be initialized only once in multithreading environment.
Computed Properties:
Classes, structures, and enumerations can define computed properties, which calculates a value rather than storing a value. They provide a getter and optional setter.
- Computed properties must have explicit type declared.
- Computed properties must always be declared as var beacuse its value is never fixed.
- Code inside the getter runs everytime the property is called.
- Setter of computed property can modify another property.
Getter declaration:
To declare the getter for computed properties you need to define properties with get{}. The getter allows you to read data from the computed property.
Whenever a computed property will be accessed its getter will be called.
Setter declaration:
To set the value of a computed property, you need to define properties with set{}. If there is no setter defined for property then you can not set its value.
Note: If a computed property’s setter doesn’t define a name for the new value to be set, a default name of newValueis used.
Read-Only Computed Properties:
A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.