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 read as follows:
class BankAccount {
var accountBalance: Float = 0
var accountNumber: Int = 0;
let fees: Float = 25.00
var balanceLessFees: Float {
get {
return accountBalance - fees
}
}
init(number: Int, balance: Float)
{
accountNumber = number
accountBalance = balance
}
.
.
.
}
The above code adds a getter that returns a computed property based on the current balance minus a fee amount. In much of the same way, an optional setter could also be declared in much the same way to set the balance value minus fees:
var balanceLessFees: Float {
get {
return accountBalance - fees
}
set(newBalance)
{
accountBalance = newBalance - fees
}
}
The new setter takes a floating-point value as a parameter from which it deducts the fee value. the result is then assigned to the current balance property. Although these are computed properties, they are accessed in the same way as stored properties using dot-notation. The following code gets the current balance less than the value of the fee before setting the property to a new value:
Get hands-on with 1400+ tech skills courses.