typestar

Classes are references in Swift

Two names, one object; === asks about identity.

// Classes are reference types: two names, one object.
final class RaceCommittee {
    var flagsFlying: [String] = []
    func hoist(_ flag: String) {
        flagsFlying.append(flag)
    }
}

let committee = RaceCommittee()
let sameCommittee = committee

committee.hoist("P")
sameCommittee.hoist("AP")

// Both names see both flags -- there is only one committee.
print("Flags: \(committee.flagsFlying)")
print("Same object: \(committee === sameCommittee)")

How it works

  1. final class opts out of inheritance it does not need.
  2. Both names reach the same instance — both flags show.
  3. === compares identity where == would compare values.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
438
Tokens
84
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 2 of 3 in Structs & classes, step 17 of 27 in Language basics.

← Previous Next →