typestar

defer in Swift

Cleanup scheduled at entry, run at every exit.

// defer schedules cleanup for scope exit, whatever the path out.
func scoreRace(entries: Int) -> String {
    print("Opening the finish log")
    defer { print("Closing the finish log") }

    guard entries > 0 else {
        return "Abandoned: empty start line"
    }
    return "Scored \(entries) finishers"
}

print(scoreRace(entries: 14))
print("---")
print(scoreRace(entries: 0))

How it works

  1. defer { ... } runs when the scope ends, success or bail.
  2. The guard's early return still triggers the deferred close.
  3. Defers read like setup and teardown side by side.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
357
Tokens
71
Three-star pace
70 tpm

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

Type this snippet

Step 3 of 3 in Errors & scope, step 24 of 27 in Language basics.

← Previous Next →

defer in other languages