Computed Properties

Last updated on 18 Oct 2024.

Written by Jia Chen.

Computed Properties

Last updated on 18 Oct 2024.

Written by Jia Chen.

Computed Properties

Last updated on 18 Oct 2024.

Written by Jia Chen.

Scroll Down

On this page

Video

On this page

What are Computed Properties?

Computed properties are properties that do not actually store a value. Instead, they allow you to supply a getter and an optional setter to define its behavior.

A computed property is a read-only computed property when it is only supplied with a getter, but not a setter.

Getters

Think of a getter as a function that runs when you call when you want to retrieve the value of the computed property.

In this example, an area computed property is declared. This provides an easier way to access the area of the Rectangle.

struct Rectangle {
    var width: Int
    var height: Int
    
    var area: Int {
        get {
            return width * height
        }
    }
}

let rect = Rectangle(width: 10, height: 20)
print(rect.area)

This can also be achieved with a function, without a computed property, however, the computed property provides a more convenient and readable way to access the Rectangle's area.

struct Rectangle {
    var width: Int
    var height: Int
    
    func getArea() -> Int {
        return width * height
    }
}

let rect = Rectangle(width: 10, height: 20)
print(rect.getArea())

Shorthand Getters

If the computed property only has a getter, you can omit the get {} clause and directly return the value. This can help make code shorter and easier to read.

struct Rectangle {
    var width: Int
    var height: Int
    
    var area: Int {
        return width * height
    }
}

If there is only one line within a getter, like functions, you can use an implicit return and omit the return keyword.

struct Rectangle {
    var width: Int
    var height: Int
    
    var area: Int {
        width * height
    }
}

Adding Setters

You can also define a setter on the computed property. Think of this like a function you can supply the computed property to handle when a user sets the value.

In the example below, the radians computed property's setter is used to update the degrees property. This allows you to set the value from both the degrees and radians property.

struct Angle {
    var degrees: Double
    var radians: Double {
        get {
            .pi * degrees / 180
        }
        set(radiansValue) {
            degrees = radiansValue * 180 / .pi
        }
    }
}

var angle = Angle(degrees: 90)

angle.radians = .pi * 2
print(angle.degrees) // Prints 360.0

Shorthand Setters

You do not need to supply a parameter name for the setter's new value. You can take advantage of the default newValue.

struct Angle {
    var degrees: Double
    var radians: Double {
        get {
            .pi * degrees / 180
        }
        set {
            degrees = newValue * 180 / .pi
        }
    }
}

Computed Properties & SwiftUI

SwiftUI uses computed properties to compose a View in the body computed property.

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
    }
}

You can also define your own computed properties as part of your SwiftUI views.

In this example, the searchResults computed property is able to filter the fruits array with the searchQuery. This makes it easier to access the filtered results.

struct ContentView: View {
    @State private var searchQuery = ""
    
    private var searchResults: [Fruit] {
        if searchQuery.isEmpty {
            return fruits
        } else {
            return fruits.filter { $0.contains(searchQuery) }
        }
    }
  
    var body: some View {
        ForEach(searchResults) {
            ...
        }
    }
}

When defining a computed property, it should not be a State variable. In the example above, when the searchQuery is updated, the searchResults computed property is automatically updated and the relevant views are re-rendered.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.