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 last3 defer { print("Closing \(name)") }4 // Defers run in reverse order: Cleanup 2 runs before Cleanup 15 defer { print("Cleanup 1") }6 defer { print("Cleanup 2") }7 8 print("Processing...")9 // Non-.txt files leave early, but the defers still run10 guard name.hasSuffix(".txt") else {11 print("Invalid file type")12 return13 }14 // Reached only for .txt files15 print("File processed successfully")16}17 // Normal path: Opening, Processing..., File processed successfully, then the three defers18processFile("data.txt")19print("---")// Early return: Invalid file type, then the same three defers20processFile("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. 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