Defer Statement in Swift

Level 3173 keystrokes

defer blocks run when the function's scope exits, in reverse order of declaration. So "Saving changes" and then "Closing file" are printed after the normal output.

Swift code

1func processFile() {
// Runs immediately: first line of output
2 print("Opening file")
// Registered first, so it runs last when the function exits
3 defer { print("Closing file") }
// Registered second, so it runs before "Closing file"
4 defer { print("Saving changes") }
// Normal statements run in order before any defer block
5 print("Processing...")
6 print("Done processing")
7}
8
// Prints Opening file, Processing..., Done processing, Saving changes, Closing file
9processFile()

Output

Opening file
Processing...
Done processing
Saving changes
Closing file
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • "× 10
  • (× 7
  • )× 7
  • .× 3
  • {× 3
  • }× 3

More Swift examples at level 3

← Swift typing practice