Swift Programming Tutorial: Computed Properties

How to Use Getters and Setters in Swift

Arc Sosangyo
3 min readNov 8, 2023
Photo by: Amol Tyagi on unsplash.com

Swift programming language computed properties stand out as a distinct type of property. They differ from conventional properties by not directly holding a value. Instead, they provide a mechanism to access or modify a value by executing custom code. In brief, it’s a property that executes code to determine its value.

Computed properties are declared using the var keyword, similar to standard properties, but they include a getter method (for obtaining the value) and, if needed, a setter method (for altering the value).

Here’s a simple example of a computer property.

struct Rectangle {
var width: Double
var length: Double

var area: Double {
return width * length
}
}

The value of the area will be based on the product of the width and length. Let’s try using the struct and print the area.

var rectangle1 = Rectangle(width: 7.10, length: 11.9)
var rectangle2 = Rectangle(width: 12.7, length: 2.3)

print(rectangle1.area)
print(rectangle2.area)

Here’s the output:

84.49
29.209999999999997

Using Getters and Setters

--

--

Arc Sosangyo

Arc is an iOS developer and app publisher, a former IT manager who transitioned to iOS engineering, and a big fan of coding, science, history, and philosophy.