Menu
Coddy logo textTech

Computed Properties

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 12 of 57.

A stored property holds a value. A computed property has no storage: it runs code each time it is read and returns a value calculated from other properties:

struct Rectangle {
    var width: Double
    var height: Double

    var area: Double {
        width * height
    }
}

var r = Rectangle(width: 3, height: 4)
print(r.area)
r.width = 10
print(r.area)

Output:

12.0
40.0

Because the value is recalculated on every read, a computed property can never be out of date. It is read like a stored property, without parentheses:

struct Person {
    var first: String
    var last: String

    var fullName: String {
        "\(first) \(last)"
    }
}

var p = Person(first: "Ada", last: "Byron")
p.last = "Lovelace"
print(p.fullName)

Output:

Ada Lovelace

A computed property can also have a setter. set receives the new value as newValue and updates the stored properties it is based on:

struct Temperature {
    var celsius: Double

    var fahrenheit: Double {
        get { celsius * 9 / 5 + 32 }
        set { celsius = (newValue - 32) * 5 / 9 }
    }
}

var t = Temperature(celsius: 100)
print(t.fahrenheit)
t.fahrenheit = 32
print(t.celsius)

Output:

212.0
0.0

Use a computed property for a value that follows from others and is cheap to calculate. Use a method when the work takes arguments or is expensive:

struct Order {
    var items: [Int]
    var total: Int { items.reduce(0, +) }           // property: no arguments
    func total(withTax rate: Int) -> Int {           // method: takes an argument
        total + total * rate / 100
    }
}
challenge icon

Challenge

Easy

Complete the struct Circle with a stored property radius and three read-only computed properties: diameter (twice the radius), area (π r², using Double.pi) and label, which returns r=2.0 d=4.0 a=12.57 with the area rounded to two decimals using String(format: "%.2f", area).

The supplied code reads one radius per line, creates a Circle, and prints label. It then doubles the radius of the last circle and prints its label again, so the values must follow the radius.

Your code goes in Circle.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
var last = Circle(radius: 0)
for line in input {
    last = Circle(radius: Double(line)!)
    print(last.label)
}
last.radius *= 2
print(last.label)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground