MasterOnce
HomeBlogHow-To
3 min readFeb 15, 2026
Swift

How to Use defer in Swift

Guarantee cleanup work at the end of a scope.

Steps

  1. Paste the code into a Swift file or playground.
  2. Run it once to verify the output.
  3. Adjust the inputs to match your use case.

Copy and paste

import Foundation

func loadResource() {
    print("Open")
    defer {
        print("Close")
    }
    print("Use resource")
}

loadResource()

Notes

  • Keep functions small and focused for reuse.
  • Prefer safe APIs like optionals and guards.