SWIFT / CHAPTER 08
Structures and classes
IntermediateChoose between value models and shared object identity.
By the end of this chapter
- Declare a struct with a mutating method
- Trace class references
- Choose a model for the domain
The idea
A struct is a value type, suitable for a small piece of data that should behave independently when copied. A method that changes a struct’s stored properties is marked mutating, and it must be called on a mutable instance. A class instead provides reference identity: two variables can refer to the same instance and observe each other’s changes.
Choose semantics from the model, not just syntax preference. A coordinate is often a useful value, while a shared live session may need identity. A let binding to a class reference prevents replacing the reference but can still allow mutation of the object’s var properties. Access control and validated methods help keep either kind of model in a meaningful state.
struct Counter {
var value = 0
mutating func add() { value += 1 }
}
var first = Counter()
var second = first
second.add()
print("(first.value):(second.value)")0:1
The struct assignment copies its value. The mutating method changes only second, whose binding was declared with var.
Try it yourself
Explain whether a saved color setting should use value semantics or shared identity, then model it.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING