Computed Properties

You can use computed properties with any class, struct, or enum that you define. Computed properties do not store values like the properties that you have been working with thus far. Instead, a computed property provides a getter and optional setter to retrieve or set the property’s value. This difference allows the value of a computed property to change, unlike the value of a lazy stored property.

Replace your definition of the townSize property on the Town type with a computed read-only property. Unlike stored read-only properties, computed read-only properties are defined using var.

Listing 16.6 Using a computed property (Town.swift)

...
lazy var townSize: Size = {
    get { switch self.population { case 0...10_000: ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.