Computed properties let you create values that are calculated when you use them, instead of storing them directly.
0
0
Adding computed properties in Swift
Introduction
When you want to show a value based on other data without storing it separately.
When you need to update a value automatically if related data changes.
When you want to keep your data consistent and avoid mistakes.
When you want to add extra information to a class or struct without extra storage.
Syntax
Swift
var propertyName: Type { get { // code to calculate and return a value } set(newValue) { // code to update other properties based on newValue } }
The get block calculates and returns the value.
The set block is optional and lets you change other data when the property is set.
Examples
A read-only computed property that combines first and last name.
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 sets 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: 3, height: 4) 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; they calculate them on demand.
Use set only if you want to allow changing related data through the computed property.
Computed properties can be used in classes, structs, and enums.
Summary
Computed properties calculate values instead of storing them.
They can have get and optional set blocks.
Use them to keep data consistent and avoid extra storage.