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
final classopts out of inheritance it does not need.- Both names reach the same instance — both flags show.
===compares identity where==would compare values.
Keywords and builtins used here
RaceCommitteeStringclassfinalfunchoistletprintvar
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.
Step 2 of 3 in Structs & classes, step 17 of 27 in Language basics.