Computed and Lazy Properties
Understand the differences between Swift stored, computed, and lazy class properties and learn how to declare them in your own code.
We'll cover the following...
Class properties in Swift fall into two categories referred to as stored properties and computed properties. Stored properties are those values that are contained in a constant or variable. Both the account name and number properties in the BankAccount
example are stored properties.
Computed properties
A computed property, on the other hand, is a value that is derived based on some form of calculation or logic at the point at which the property is set or retrieved. Computed properties are implemented by creating getter and optional corresponding setter methods containing the code to perform the computation. For example, consider that the BankAccount
class might need an additional property to contain the current balance after any recent banking fees. Rather than use a stored property, it makes more sense to use a computed property that calculates this value on request. The modified BankAccount
class might now ...