Consider the following Swift code snippet. What will be printed when it runs?
func testDefer() { print("Start") defer { print("Deferred 1") } defer { print("Deferred 2") } print("End") } testDefer()
Remember that defer statements run in reverse order when the function exits.
Defer blocks execute in last-in, first-out order when the function returns. So the second defer runs before the first.
What is the value of count after running this Swift code?
func countTest() -> Int { var count = 0 defer { count += 1 } count += 2 return count } let result = countTest() print(result)
Defer runs after the return value is set but before the function fully exits.
The return value is set to 2 before defer runs. The defer increments count to 3, but this does not affect the returned value.
Examine the code below. Why does the defer block not print anything?
func earlyExit() { defer { print("Cleanup") } return print("This will not print") } earlyExit()
Defer always runs when exiting the current scope, even if return is called.
Defer blocks run when the function exits, even if return is called early. So "Cleanup" is printed.
What will be printed by this Swift code?
class Counter { var value = 0 } func modifyCounter() { let counter = Counter() defer { counter.value += 10 print("Deferred value: \(counter.value)") } counter.value += 5 print("Current value: \(counter.value)") } modifyCounter()
Defer runs after the print of current value, so it sees the updated value.
The counter's value is 5 when printed first. Then defer adds 10 and prints 15.
Consider this Swift code. How many times will the defer block run?
func loopDefer() { for i in 1...3 { defer { print("Deferred in iteration \(i)") } print("Loop iteration \(i)") } } loopDefer()
Defer runs when the current scope exits. What is the scope of the defer inside the loop?
The defer is inside the loop's scope, so it runs once per iteration when that iteration's scope ends.