Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 146 ยท Structures, Classes and Enums

Properties

Learn Swift properties - stored and computed, let vs var, lazy properties, willSet and didSet observers, type properties with static, and the real compiler errors you will meet along the way.

A property is a value that belongs to a type. A Rectangle has a width and a height, a User has a name and an email, a Thermostat has a target temperature. Almost every struct, class and enum you write in Swift is built from properties plus the methods that work on them.

Swift is generous here: some properties simply hold a value, some calculate their value every time you ask, some wait until the first time you need them, and some run your code whenever they change. This lesson walks through all of them, shows the compiler errors beginners hit, and ends with the rules for properties that belong to the type instead of to one instance.

Stored properties

A stored property keeps a value in memory as part of the instance. You declare it with var (can change) or let (fixed once the instance exists), and you can give it a default value right at the declaration.

Swift Stored properties with and without defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice that Player(name: "Ada") only asks for name. Swift builds a memberwise initializer for structs, and properties that already have a default value become optional arguments. You will meet initializers properly in Initializers.

let properties and let instances

A let property can never change after the instance is initialized. That part is easy. The surprise for newcomers is what happens when you store a struct in a let constant: the whole value becomes immutable, including its var properties.

Swift Mutating a let struct (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler refuses with cannot assign to property: 'counter' is a 'let' constant. The fix is to declare the constant with var. This rule exists because a struct is a value: if the value is constant, all of it is constant. A class instance behaves differently, because the constant holds a reference and the object it points to can still change. Classes and Value vs. Reference Semantics explain why.

A stored let property without a default value must be assigned exactly once during initialization. After that, any attempt to change it is a compile error, no matter whether the instance lives in a var or a let.

Computed properties

A computed property stores nothing. Each time you read it, Swift runs a block of code and returns the result. Computed properties are always var, because their value is not fixed, and they must declare a type.

Swift Computed properties: area and diameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

area only has a getter, so it is read-only; when the body is a single expression you can drop the word return, and even the get keyword. diameter has both a getter and a setter. Inside the setter, the incoming value is called newValue unless you name it yourself: set(newDiameter) { ... }.

Why use a computed property instead of a stored one? Because it can never go out of date. If you stored area and then changed radius, the stored number would be wrong until you remembered to update it. A computed property recalculates, so there is only one source of truth.

Compute cheap things, store expensive things. A computed property that loops over a million elements on every access looks like a plain variable but costs like a function call. If the work is heavy, make it a method (func total() -> Int), or cache it with a lazy property.

Assigning to a read-only computed property

A computed property without a setter is read-only, and the compiler enforces it.

Swift Writing to a read-only property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is cannot assign to property: 'area' is a get-only property. Either give area a setter that works out the new side (the square root of the area), or change side instead.

Lazy stored properties

Sometimes a property is expensive to build and you might never need it. Mark it lazy and Swift creates the value on the first access, not when the instance is created. A lazy property must be a var with a default value expression.

Swift lazy: built only when first used

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read the output in order: "Report created" appears first, the build message appears only when body is first read, and the second access reuses the stored result. Remember three limits of lazy:

  • It needs var, because the property changes from "empty" to "filled" after creation. That also means reading it from a let struct is not allowed.
  • Reading it can mutate the instance, so for a struct the accessing code needs a var.
  • It is not automatically safe to touch from several threads at once. Use it for single-owner data, and see Actors and Shared State for sharing.

Property observers

An observer runs your code whenever a stored property's value is set. willSet runs just before the change (with the incoming value as newValue) and didSet runs just after (with the previous value as oldValue). You can use either or both.

Swift willSet and didSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Setting target inside its own didSet is allowed and does not trigger the observers a second time, which is why the clamping works. A few more rules worth memorizing:

  • Observers fire even when the new value equals the old value. Swift does not compare them for you.
  • Observers are not called while the instance is being initialized, only for later assignments.
  • Observers are for stored properties. For a computed property, put the extra code in the setter.
  • You can attach observers to an inherited property in a subclass; see Inheritance.
Swift Observers are skipped during init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Type properties

Everything so far was an instance property: every instance has its own copy. A type property belongs to the type itself, so there is exactly one of it. You declare it with static.

Swift static properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You reach a type property through the type name (Temperature.range), never through an instance. Inside the type you can also write Self.boilingPoint, where Self means "the current type".

Static stored properties are lazily initialized, exactly once, and Swift guarantees that initialization is thread-safe. That is why static let shared = Service() is the standard way to write a singleton.

A static var is global mutable state in disguise, and Swift 6 treats it that way:

Swift A mutable static property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with static property 'conversions' is not concurrency-safe because it is nonisolated global shared mutable state, because two threads could change it at the same moment. Its notes offer three exits: make it a let, pin it to the main actor with @MainActor, or promise safety yourself with nonisolated(unsafe). The first is best, the second works for UI-style code, and the third is a promise you must keep by hand (see Actors).

Swift Fix: isolate the counter to the main actor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Top-level code in main.swift runs on the main actor, so it may use a @MainActor type directly. Code on other threads would have to await it first.

Classes have one extra option: class var for a type computed property that subclasses may override, while static means "cannot be overridden".

Property wrappers, briefly

If you find yourself writing the same didSet clamp on many properties, a property wrapper packages that rule into a reusable type and you attach it with an attribute such as @Clamped. Wrappers are covered in their own lesson, Property Wrappers; for now know that @Something var x is still just a property, with its storage rules supplied by a type.

Choosing the right kind of property

You need... Use
A value that is set once and never changes let stored property
A value that changes over time var stored property
A value derived from other properties computed property
An expensive value you may never need lazy var
Code to run when a value changes willSet / didSet
One value shared by every instance static property

Two habits will serve you well. First, prefer let and let the compiler tell you when you truly need var. Second, keep your properties consistent: when two stored values must always agree (such as width, height and area), store the independent ones and compute the dependent one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is wrong with let c = Counter(); c.count = 5 when Counter is a struct with var count?

    A struct is a value type. If the constant holds the value, none of its properties can change, even var ones. Declare it with var instead.
  2. 2. When is the closure of a lazy var property run?

    A lazy property is built on first access and the result is stored, so later reads reuse it.
  3. 3. Which statement about didSet is true?

    didSet runs after each assignment (even to an equal value) and gives you oldValue. It is skipped inside the type's own initializers, and a computed property uses its setter instead.
  4. 4. How do you read a static property maxLevel of struct Game from outside the type?

    Type properties belong to the type, so you access them through the type name.
  5. 5. Why is a computed area usually better than a stored area next to width and height?

    A computed property is recalculated on every read, so it always matches its inputs. Speed depends on the calculation.

Summary

  • Stored properties hold values (let fixed, var changeable) and may have defaults.
  • A struct in a let constant is fully immutable, var properties included.
  • Computed properties calculate on every read; without a setter they are get-only.
  • lazy var builds its value on first access and keeps it.
  • willSet and didSet observe stored properties but are skipped during initialization.
  • static properties belong to the type, are initialized once and lazily; mutable ones are risky in Swift 6.
  • Wrappers like @Clamped reuse property rules; see the Property Wrappers lesson.

Next: Methods