What is defer?
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