0
0
Swiftprogramming~5 mins

Computed properties in Swift

Choose your learning style9 modes available
Introduction

Computed properties let you create values that are calculated when you need them, not stored directly. They help keep your data fresh and up-to-date automatically.

When you want a value that depends on other values and should update automatically.
When you want to simplify your code by avoiding manual updates to related values.
When you want to add extra logic to getting or setting a value.
When you want to keep your data consistent without storing extra variables.
Syntax
Swift
var propertyName: Type {
    get {
        // return a computed value
    }
    set(newValue) {
        // update other properties based on newValue
    }
}

The get block calculates and returns the value.

The set block updates other properties when you assign a new value.

Examples
A read-only computed property that combines first and last names.
Swift
var fullName: String {
    return "\(firstName) \(lastName)"
}
A computed property with both get and set to convert age in years to months and back.
Swift
var ageInMonths: Int {
    get {
        return age * 12
    }
    set(newMonths) {
        age = newMonths / 12
    }
}
Sample Program

This program defines a rectangle with computed properties for area and perimeter. Changing the perimeter updates width and height to make a square.

Swift
struct Rectangle {
    var width: Double
    var height: Double

    var area: Double {
        return width * height
    }

    var perimeter: Double {
        get {
            return 2 * (width + height)
        }
        set(newPerimeter) {
            let side = newPerimeter / 4
            width = side
            height = side
        }
    }
}

var rect = Rectangle(width: 4, height: 5)
print("Area: \(rect.area)")
print("Perimeter: \(rect.perimeter)")

rect.perimeter = 20
print("New width: \(rect.width)")
print("New height: \(rect.height)")
OutputSuccess
Important Notes

Computed properties do not store values themselves; they calculate them on demand.

You can omit the get keyword if the property is read-only and just return the value directly.

Use set only if you want to allow changing the computed property.

Summary

Computed properties calculate values dynamically instead of storing them.

They can have a getter to return a value and an optional setter to update related data.

They help keep your data consistent and your code clean.