Exploring Computed Properties in Swift

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

by The Captain

on
May 25, 2024

Computed Properties in Swift

Computed properties in Swift allow you to define a property that does not actually store a value but instead provides a getter and an optional setter that can be used to retrieve and set other property values or perform calculations. Computed properties are useful when you want to provide additional functionality beyond simple storage of values.

Here's an example of how to define a computed property in Swift:

struct Circle {
    var radius: Double
    
    var area: Double {
        return Double.pi * radius * radius
    }
}

let circle = Circle(radius: 5.0)
print("The area of the circle is \(circle.area)")}
In the code snippet above, we have a `Circle` struct with a `radius` property and a computed property `area`. The `area` property calculates and returns the area of the circle using the formula for the area of a circle (π * radius²). Computed properties can be either read-only (with only a getter) or read-write (with both a getter and a setter). When defining a read-only computed property, you only need to provide a getter. For read-write computed properties, you need to provide both a getter and a setter. Computed properties are a powerful feature in Swift that allows for more flexibility and control over how properties are accessed and manipulated in your code.