Managing Properties in Swift: Stored, Computed, and Property Observers

A portrait painting style image of a pirate holding an iPhone.

by The Captain

April 18, 2024

Working with Properties in Swift

In Swift, properties are used to store values and provide access to them within a class, structure, or enumeration. Properties in Swift can be stored properties, computed properties, or property observers.

Stored Properties

Stored properties are constants or variables that are stored as part of an instance of a class or structure. They can be assigned an initial value, and their value can be changed during the instance's lifetime. Here is an example of a stored property:

class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) { = name
        self.age = age

let person = Person(name: "John", age: 30)
print( // Output: John}

Computed Properties

Computed properties do not store a value directly but provide a getter and an optional setter to retrieve and set other properties or values. Computed properties are used to perform additional computation or processing to derive their value. Here is an example of a computed property:

struct Rectangle {
    var width: Double
    var height: Double
    var area: Double {
        return width * height

let rect = Rectangle(width: 5.0, height: 3.0)
print(rect.area) // Output: 15.0}

Property Observers

Property observers monitor and respond to changes in a property's value. They can be added to stored properties and are called before a new value is set or after it has been set. There are two types of property observers: `willSet` and `didSet`. Here is an example using `willSet`:

class Temperature {
    var celsius: Double = 0 {
        willSet {
            print("Changing temperature to \(newValue) degrees Celsius")

let temp = Temperature()
temp.celsius = 25 // Output: Changing temperature to 25.0 degrees Celsius}

Working with properties in Swift allows you to encapsulate and manage data in a structured and efficient manner, providing more control and functionality to your code.