O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required