typestar

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

  1. struct Tally gets a memberwise-style default init.
  2. mutating func score may write points.
  3. The copy taken before the last score never sees it.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Structs & classes, step 16 of 27 in Language basics.

← Previous Next →