0Pricing
Swift Academy · Lesson

defer with Errors and Early Returns

Ensure cleanup even when throwing or returning early.

defer Runs on return

A defer block runs even when the function exits early via return.

func check(_ value: Int) {
    defer { print("cleanup ran") }
    if value < 0 {
        print("negative, returning early")
        return
    }
    print("value is", value)
}
check(-5)

Cleanup on Every Path

No matter which return fires, the deferred cleanup runs exactly once.

func classify(_ n: Int) {
    defer { print("done classifying") }
    if n == 0 { print("zero"); return }
    if n > 0 { print("positive"); return }
    print("negative")
}
classify(0)

All lessons in this course

  1. How defer Works
  2. Multiple defer Blocks Ordering
  3. defer for Resource Cleanup
  4. defer with Errors and Early Returns
← Back to Swift Academy