Coding/Learn/swift/swift properties and methods
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnProperties: Stored, Computed, Observers (didSet) & Lazy
17 / 20 0%
Lesson 17 of 20
9 mins read

Properties: Stored, Computed, Observers (didSet) & Lazy

PreviousNext Lesson
In Plain English

Properties associate values with structures, classes, and enumerations. Learn Stored vs Computed properties, Property Observers (willSet and didSet) for responding to state changes, lazy stored properties for deferred initialization, and static type properties.

The Mental Model

"A stored property is a physical storage shelf. A computed property is an electronic calculator on the wall that computes a value dynamically whenever you press the button. A property observer (didSet) is an alarm sensor that rings whenever a new package is placed on the shelf."

Deep Dive: How It Works

Computed Properties: var prop: Type { get { ... } set(newVal) { ... } } calculates a value dynamically rather than storing it.

Property Observers: didSet { ... } executes immediately after a new value is stored; willSet { ... } executes right before.

lazy Stored Properties: lazy var data = loadHugeFile() delays initialization until the property is first accessed.

Static Properties: static let maxLimit = 100 defines a type-level constant shared across all instances.

Syntax Blueprint

var score: Int = 0 {
    didSet { print("Score changed from \(oldValue) to \(score)") }
}
var doubleScore: Int { score * 2 }

Use didSet to monitor property mutations and var name: Type { ... } for computed getters.

PointCore Rules to Remember

Point star
oldValue and newValue: didSet provides automatic access to oldValue; willSet provides access to newValue.
Point star
Read-Only Computed Properties: You can omit the get keyword for read-only computed properties (var area: Double { w * h }).
Point star
lazy Must Be var: lazy properties must always be declared with var because their initial value might not be set until after instance initialization.

Common Beginner Traps & How to Fix Them

Mistake:Assigning to a property inside its own didSet observer without a guard condition.

Why it happens: Can trigger recursive observer loops if not carefully managed.

How to fix: Avoid self-assignment in didSet or use computed getters.

Pro Tip: Use computed properties instead of getMethod() functions when a calculation is lightweight (O(1)) and has no side-effects.

Live Interactive Example

Hit Run Code to see it live
Computed Properties and Property Observers
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Output Console
Click "Run Code" to view the rendered output.
How it works: didSet fired automatically on each score change, and isHighScore dynamically computed true.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Implement Step Counter with didSet

  • PointDefine a struct StepTracker with var totalSteps: Int = 0.
  • PointAdd a didSet observer to totalSteps that prints "Steps increased to \(totalSteps)".
  • PointIn top-level code, create var tracker = StepTracker() and set tracker.totalSteps = 1000.
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates