Structs are values in Swift
Assignment copies; writers say mutating.
// Structs are value types: assignment copies, and a method that
// writes needs the mutating keyword.
struct Tally {
var points = 0
mutating func score(place: Int) {
points += max(0, 10 - place)
}
}
var kestrel = Tally()
kestrel.score(place: 1)
kestrel.score(place: 3)
var copyBefore = kestrel
kestrel.score(place: 2)
print("Kestrel: \(kestrel.points) points")
print("The copy stayed at \(copyBefore.points)")
How it works
struct Tallygets a memberwise-style default init.mutating func scoremay writepoints.- The copy taken before the last score never sees it.
Keywords and builtins used here
IntTallyfuncmaxmutatingprintscorestructvar
The run, in numbers
- Lines
- 18
- Characters to type
- 413
- Tokens
- 89
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 76 seconds.
Step 1 of 3 in Structs & classes, step 16 of 27 in Language basics.