0
0
Swiftprogramming~5 mins

Defer statement for cleanup in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the defer statement in Swift?
The defer statement schedules code to run just before the current scope exits, ensuring cleanup code runs no matter how the scope is exited.
Click to reveal answer
beginner
When exactly does the code inside a defer block execute?
The code inside a defer block executes right before the function or scope returns or exits, even if an error is thrown or a return happens earlier.
Click to reveal answer
intermediate
Can multiple defer statements be used in the same scope? If yes, in what order do they execute?
Yes, multiple defer statements can be used. They execute in reverse order of appearance (last-in, first-out).
Click to reveal answer
beginner
Why is defer useful for resource management?
defer ensures resources like files or network connections are properly closed or released, even if the function exits early or throws an error.
Click to reveal answer
beginner
Example: What will this Swift code print?
func test() {
  defer { print("Cleanup") }
  print("Start")
  return
  print("End")
}
test()
It will print:<br>Start<br>Cleanup<br>The defer block runs after print("Start") and before the function returns. The print("End") is never reached.
Click to reveal answer
What happens if a function with a defer block throws an error?
AThe function ignores the error.
BThe <code>defer</code> block is skipped.
CThe <code>defer</code> block still runs before the error propagates.
DThe program crashes immediately.
If you have two defer blocks in a function, which one runs first?
AOnly the last one runs.
BThe first one written in the code.
CThey run simultaneously.
DThe second one written in the code.
Which of these is a good use case for defer?
ADeclaring a variable.
BOpening a file and ensuring it closes after use.
CStarting a loop.
DPrinting a message at the start of a function.
What will this code print?
func example() {
  defer { print("First") }
  defer { print("Second") }
  print("Hello")
}
example()
AHello\nSecond\nFirst
BFirst\nSecond\nHello
CSecond\nHello\nFirst
DHello\nFirst\nSecond
Can defer be used outside of functions, like in global scope?
ANo, only inside functions or methods.
BYes, anywhere in code.
COnly inside loops.
DOnly inside classes.
Explain how the defer statement helps with cleanup in Swift functions.
Think about what happens when a function ends early or throws an error.
You got /4 concepts.
    Describe the order of execution when multiple defer statements are used in the same function.
    Imagine stacking plates and removing them one by one.
    You got /4 concepts.