Tools
Log in
English

Learn to codeSwift

Swift composition and static

Based on Swift 6.4switch 식 · Swift 5.9+

Swift composition, static members, enums with associated values, ARC and weak.

In one line

Composition means a larger object holds smaller ones as properties and hands them parts of the work. static members belong to the type itself rather than to each object. Swift’s ARC decides when objects are freed, so two objects that point at each other need a weak link.

Why you need it

Making the team inherit from the player would claim that a team is a kind of player. Listing player names and roles as fields on the team class shakes the team code whenever a player changes.

The team holds an array of players, and each player holds a role (an enum). A rule shared by everyone (the maximum size) sits once in a static let. With the back-pointing team marked weak, both sides are freed cleanly when the team is no longer needed.

Everyday picture

Think of a club roster. The club (the team) keeps the member list (the player array), and each member carries a note saying which club they belong to (weak). If the club disbands, the note simply goes blank. "At most five members" (static) is written in the club rules, not on each member.

Example code

main.swift · 69 lines
var club: Team? = Team(name: "Owls")club?.add(Player(name: "Mia", role: .keeper))club?.add(Player(name: "Leo", role: .striker(number: 9)))if let team = club {    print(team.lineup())    print("limit \(Team.maxPlayers), code \(Team.code(for: team.name))")}club = nilprint("done") enum Role {    case keeper    case defender    case striker(number: Int)     var label: String {        switch self {        case .keeper: "GK"        case .defender: "DF"        case .striker(let number): "FW#\(number)"        }    }} final class Player {    let name: String    let role: Role    weak var team: Team?     init(name: String, role: Role) {        self.name = name        self.role = role    }     deinit {        print("\(name) released")    }} final class Team {    static let maxPlayers = 5     let name: String    private(set) var players: [Player] = []     init(name: String) {        self.name = name    }     static func code(for name: String) -> String {        String(name.prefix(3)).uppercased()    }     func add(_ player: Player) {        guard players.count < Team.maxPlayers else {            return        }        player.team = self        players.append(player)    }     func lineup() -> String {        players.map { "\($0.name)(\($0.role.label))" }.joined(separator: ", ")    }     deinit {        print("\(name) released")    }}

When to use it

  • "X has a Y" makes sense: composition (a team has players)
  • Constants and factory helpers shared by all objects: static let and static func
  • A value is one of a few choices and each choice carries different data: an enum with associated values
  • Two classes point at each other: make one side weak

Using a switch itself as a value, as in case .keeper: "GK" (a switch expression), works from Swift 5.9.

Structs and enums are value types, so ARC does not track them. Reference cycles happen only between classes.

Common mistakes

A strong reference cycle

If the squad holds the captain and the captain holds the squad with normal references, squad = nil frees neither: they keep each other alive and deinit never runs. Make one side weak, usually the child or back-pointing side. Use unowned when you can promise the value is always there.

Wrong

var squad: Squad? = Squad(name: "Reds")squad?.captain = Captain(name: "Bo", squad: squad)squad = nilprint("end") final class Squad {    let name: String    var captain: Captain?     init(name: String) {        self.name = name    }     deinit {        print("\(name) released")    }} final class Captain {    let name: String    var squad: Squad?     init(name: String, squad: Squad?) {        self.name = name        self.squad = squad    }     deinit {        print("\(name) released")    }}

When you run itend

Fixed

var squad: Squad? = Squad(name: "Reds")squad?.captain = Captain(name: "Bo", squad: squad)squad = nilprint("end") final class Squad {    let name: String    var captain: Captain?     init(name: String) {        self.name = name    }     deinit {        print("\(name) released")    }} final class Captain {    let name: String    weak var squad: Squad?     init(name: String, squad: Squad?) {        self.name = name        self.squad = squad    }     deinit {        print("\(name) released")    }}

When you run itReds released Bo released end

A plain static var in Swift 6

Swift 6 language mode rejects shared values that several tasks could change at once. Use static let for values that never change; for values that must change, add @MainActor so only the main actor touches them. Top-level code runs on the main actor, so it can use it as is.

Wrong

Tally.count += 1print(Tally.count) enum Tally {    static var count = 0}

What the Swift compiler sayserror: static property 'count' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]

Fixed

Tally.count += 1print(Tally.count) enum Tally {    @MainActor static var count = 0}

When you run it1

Comparing an enum with associated values using ==

An enum whose cases carry data has no == until it conforms to Equatable. To check the case and pull out its data, match a pattern: if case .striker(let number) = role.

Wrong

let role = Role.striker(number: 7)if role == .striker(number: 7) {    print("forward")}

What the Swift compiler sayserror: binary operator '==' cannot be applied to two 'Role' operands

Fixed

let role = Role.striker(number: 7)if case .striker(let number) = role {    print("forward #\(number)")}

When you run itforward #7

Check yourself

Question 1

What is the label of a striker wearing 7?

print(Role.striker(number: 7).label)

Show the answer

Answer: 2. FW#7 The case .striker(let number) branch in label pulls out the carried 7 and builds FW#7.

Question 2

The team lives only inside do { }. After the block, what is su.team == nil?

let su = Player(name: "Su", role: .defender)do {    let hawks = Team(name: "Hawks")    hawks.add(su)}print(su.team == nil)

Show the answer

Answer: 1. true When the block ends, the only constant holding the team disappears and the team is freed (Hawks released). The player’s team is weak, cannot keep it alive, and becomes nil.

Questions people ask

What is ARC?

Automatic reference counting. Swift tracks how many strong references point to a class object and frees it the moment that number hits zero, calling deinit. Unlike a garbage collector, it does not run separately; cleanup happens right there.

How do I choose between weak and unowned?

Use weak when the other object may disappear first: it becomes an optional and turns nil. Use unowned only when you can promise the other object always outlives this one; a broken promise crashes.

When are associated values useful?

When a value is one of a few cases and each case carries different data, like a shirt number only strikers have. Read them by matching a pattern with switch or if case.