Properties in Swift

An Introduction to Stored and Computed Properties in Swift

Pavlos Simas
2 min readDec 16, 2022
Photo by Maxwell Nelson on Unsplash

Properties in Swift are used to store values and associate them with a particular instance of a type. There are two main types of properties in Swift: stored properties and computed properties.

Stored properties are variables or constants that are associated with an instance of a type and stored as part of that instance. They can be either variable or constant, depending on whether they are declared with the var or let keyword. For example:

struct Point {
var x: Double
var y: Double
}

let point = Point(x: 0, y: 0)
point.x = 10
point.y = 20

Computed properties, on the other hand, do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties or variables. The value of a computed property is calculated every time it is accessed. For example:

struct Rectangle {
var origin: Point
var size: Size
var center: Point {
get {
Point(x: origin.x + size.width / 2, y: origin.y + size.height / 2)
}
set(newCenter) {
origin.x = newCenter.x - size.width / 2
origin.y = newCenter.y - size.height / 2
}
}
}

var rect = Rectangle(origin: Point(x: 0, y: 0), size: Size(width: 10, height…

--

--

Pavlos Simas

iOS Developer, with passion about Development, Marketing and Finance. Join Medium from the following link: https://simaspavlos.medium.com/membership