DevPrep

All topics › The Swift Language

What is defer?

Junior PRO

The idea

defer { ... } is a block that runs on any exit from the current scope: normal end of the block, return, throw, break, continue. It is for guaranteed cleanup: close a file, release a lock, end a beginBackgroundTask, reset an isLoading flag.

func process() throws {
    print("open")
    defer { print("close 1") }
    defer { print("close 2") }
    print("work")
}
try process()
// open
// work
// close 2
// close 1

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store