Defer Statement in Swift

Level 5353 keystrokes

defer blocks run whenever the function exits, whether it reaches the end or returns early from guard. They run in reverse order, so each call ends with Cleanup 2, Cleanup 1 and Closing.

Swift code

1func processFile(_ name: String) {
2 print("Opening \(name)")
// Registered first, so it runs last
3 defer { print("Closing \(name)") }
4
// Defers run in reverse order: Cleanup 2 runs before Cleanup 1
5 defer { print("Cleanup 1") }
6 defer { print("Cleanup 2") }
7
8 print("Processing...")
9
// Non-.txt files leave early, but the defers still run
10 guard name.hasSuffix(".txt") else {
11 print("Invalid file type")
12 return
13 }
14
// Reached only for .txt files
15 print("File processed successfully")
16}
17
// Normal path: Opening, Processing..., File processed successfully, then the three defers
18processFile("data.txt")
19print("---")
// Early return: Invalid file type, then the same three defers
20processFile("image.png")

Output

Opening data.txt
Processing...
File processed successfully
Cleanup 2
Cleanup 1
Closing data.txt
---
Opening image.png
Processing...
Invalid file type
Cleanup 2
Cleanup 1
Closing image.png
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.

  • "× 22
  • (× 14
  • )× 14
  • .× 7
  • {× 5
  • }× 5
  • -× 3
  • \× 2
  • _× 1
  • :× 1

More Swift examples at level 5

← Swift typing practice