Line At A Time
Lesson 5: The mutating Keyword
The mutating Keyword Change a struct's values; Swift makes you say so.
1struct Dog {
2 var name: String
3 var age: Int
4
5 mutating func birthday() {
6 age = age + 1
7 print("\(name) is now \(age)!")
8 }
9}
10
11var rex = Dog(name: "Rex", age: 3)
12rex.birthday()
13rex.birthday()
Terminal
$ swift main.swift
Rex is now 4!
Rex is now 5!
Every line, explained
struct Dog {
struct Dog { ... } defines a struct: a blueprint bundling values that belong together. Swift developers reach for structs first when they want to model a "thing".
var name: String
A variable inside a struct is called a property; every Dog gets its own.
var age: Int
This one will change.
mutating func birthday() {
A struct method that CHANGES the struct's own properties must be marked mutating; Swift makes changes loud and visible, on purpose. It is part of the same safety thinking as let vs var.
age = age + 1
Adds 1 to this dog's stored age. The value is remembered.
print("\(name) is now \(age)!")
print(...) works exactly as in Intro to Swift.
}
This } closes the method.
}
This } closes the struct.
var rex = Dog(name: "Rex", age: 3)
Notice: var, not let! A dog whose properties will change must be a var; a let dog is locked solid, and Swift would refuse the birthday() call.
rex.birthday()
First birthday: 3 becomes 4.
rex.birthday()
Second birthday: rex remembered being 4, so now he is 5.