When to use computed properties or methods in Swift

Feb 26, 2024#swift

Computed properties in Swift are used when you want to calculate a value rather than storing it directly. They allow you to define a getter (and optionally a setter) for a property, and the value is computed on the fly when the property is accessed. If you don’t provide a setter, they become read-only properties.

A method is a function that is associated with a particular type, such as a class, structure, or enumeration. Methods are used to define behavior and functionality related to instances of a type.

Choosing between computed properties and methods depends on the nature of the data you are working with and the intended use case. Here are some considerations to help you decide when to use computed properties over methods:

Primary purpose

Both computed properties and methods can provide dynamic behavior, allowing you to calculate values or perform actions based on the current state of an instance.

Computed properties are primarily used for defining properties that are calculated or derived based on the current state of an instance. Computed properties give the impression of accessing a stored value, but they are calculated on-the-fly.

struct Person {
    var firstName: String
    var lastName: String
    
    var fullName: String {
        get {
            return "\(firstName) \(lastName)"
        }
        set {
            let parts = newValue.components(separatedBy: " ")
            firstName = parts[0]
            lastName = parts[1]
        }
    }
}

var person = Person(firstName: "John", lastName: "Doe")
print(person.fullName) // Output: John Doe

person.fullName = "Jane Smith"
print(person.firstName) // Output: Jane
print(person.lastName) // Output: Smith

Methods are used for defining actions or operations associated with a type or instance. Methods are explicitly called to perform a task.

extension Person {
    func greet(lastName: String? = nil) {
        var greeting = "Hello, " + firstName
        if let lastName = lastName {
            greeting += " \(lastName)"
        }
        print(greeting)
    }
}

var person = Person(firstName: "John", lastName: "Doe")
person.greet() // Output: Hello, John
person.greet(lastName: "Doe") // Output: Hello, John Doe

Access syntax

Computed properties provide a clean and concise syntax, allowing you to access them like regular properties. This can lead to more readable code compared to calling a method.

var person = Person(firstName: "John", lastName: "Doe")

// Computed property
print(person.fullName) // Output: John Doe

// Method
person.greet(lastName: "Doe") // Output: Hello, John Doe

Side effects

Use computed properties when the operation represents a property of the instance. Computed properties suggest that they are lightweight and don’t have side effects.

struct Rectangle {
    var width: Double
    var height: Double

    // Computed property
    var area: Double {
        return width * height
    }
}

If the operation has side effects or involves complex computations that may take a significant amount of time, using a method is often more appropriate. Methods explicitly indicate that they perform an action.

struct DataProcessor {
    var data: [Int]

    // Method
    mutating func processData() {
        // Perform complex data processing
        // ...
    }
}

Parameterized operations

If the operation requires parameters, methods are a natural choice. Computed properties are more suitable for operations that depend solely on the instance’s internal state.

struct Point {
    let x: Double
    let y: Double
    
    func distanceTo(other: Point) -> Double {
        let xDistance = x - other.x
        let yDistance = y - other.y
        return sqrt(xDistance * xDistance + yDistance * yDistance)
    }
}

let p1 = Point(x: 1, y: 2)
let p2 = Point(x: 4, y: 5)
let distance = p1.distanceTo(other: p2)