#50: defer in Swift

defer lets you register code that will run when the current scope exits. That includes normal returns, early returns and thrown errors.

func load() throws {
    lock.lock()
    defer { lock.unlock() }

    try readConfiguration()
    try readDatabase()
}

This is a neat way to keep setup and teardown close together instead of scattering cleanup logic across multiple exit paths.

defer is especially useful for locks, temporary state changes, transactions and file handles.


I'm also on Twitter and GitHub.

Subscribe via RSS.