Bird
Raised Fist0
Swiftprogramming~20 mins

Defer statement for cleanup in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Defer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code using defer?

Consider the following Swift code snippet. What will be printed when it runs?

Swift
func testDefer() {
    print("Start")
    defer {
        print("Deferred 1")
    }
    defer {
        print("Deferred 2")
    }
    print("End")
}
testDefer()
A
Start
End
Deferred 2
Deferred 1
B
Start
End
Deferred 1
Deferred 2
C
Deferred 1
Deferred 2
Start
End
D
Start
Deferred 1
Deferred 2
End
Attempts:
2 left
💡 Hint

Remember that defer statements run in reverse order when the function exits.

❓ Predict Output
intermediate
2:00remaining
What happens if defer modifies a variable?

What is the value of count after running this Swift code?

Swift
func countTest() -> Int {
    var count = 0
    defer {
        count += 1
    }
    count += 2
    return count
}
let result = countTest()
print(result)
A0
B1
C2
D3
Attempts:
2 left
💡 Hint

Defer runs after the return value is set but before the function fully exits.

🔧 Debug
advanced
2:00remaining
Why does this defer block not execute?

Examine the code below. Why does the defer block not print anything?

Swift
func earlyExit() {
    defer {
        print("Cleanup")
    }
    return
    print("This will not print")
}
earlyExit()
AThe defer block is skipped because return is before it.
BThe defer block runs before return and prints "Cleanup".
CThe defer block runs but print output is buffered and not shown.
DThe defer block is ignored because it is after the return statement.
Attempts:
2 left
💡 Hint

Defer always runs when exiting the current scope, even if return is called.

❓ Predict Output
advanced
2:00remaining
What is the output when defer modifies a reference type?

What will be printed by this Swift code?

Swift
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()
A
Current value: 15
Deferred value: 15
B
Current value: 5
Deferred value: 5
C
Deferred value: 15
Current value: 5
D
Current value: 5
Deferred value: 15
Attempts:
2 left
💡 Hint

Defer runs after the print of current value, so it sees the updated value.

🧠 Conceptual
expert
2:00remaining
How many times is the defer block executed in this loop?

Consider this Swift code. How many times will the defer block run?

Swift
func loopDefer() {
    for i in 1...3 {
        defer {
            print("Deferred in iteration \(i)")
        }
        print("Loop iteration \(i)")
    }
}
loopDefer()
A3 times, once after each loop iteration
B6 times, twice per iteration
C0 times, defer inside loop is ignored
D1 time, after the entire loop finishes
Attempts:
2 left
💡 Hint

Defer runs when the current scope exits. What is the scope of the defer inside the loop?

Practice

(1/5)
1. What does the defer statement do in Swift?
easy
A. Skips the rest of the function
B. Runs code just before the function returns
C. Runs code immediately when the function starts
D. Runs code only if an error occurs

Solution

  1. Step 1: Understand the purpose of defer

    The defer statement schedules code to run at the end of the current function, just before it returns.
  2. Step 2: Compare options with this behavior

    Only Runs code just before the function returns matches this behavior exactly; others describe different timings or conditions.
  3. Final Answer:

    Runs code just before the function returns -> Option B
  4. Quick Check:

    defer runs code before function ends = C [OK]
Hint: Remember: defer runs code at function exit, not start [OK]
Common Mistakes:
  • Thinking defer runs immediately
  • Confusing defer with error handling
  • Assuming defer skips code
2. Which of the following is the correct syntax to use a defer statement in Swift?
easy
A. defer -> { print("Cleanup") }
B. defer: print("Cleanup")
C. defer() print("Cleanup")
D. defer { print("Cleanup") }

Solution

  1. Step 1: Recall correct defer syntax

    The defer statement uses the keyword followed by a block in curly braces: defer { ... }.
  2. Step 2: Check each option

    Only defer { print("Cleanup") } matches the correct syntax. Others use invalid punctuation or structure.
  3. Final Answer:

    defer { print("Cleanup") } -> Option D
  4. Quick Check:

    defer uses braces {} for code block = D [OK]
Hint: defer always uses braces { } for its code block [OK]
Common Mistakes:
  • Using parentheses instead of braces
  • Adding colons after defer
  • Using arrow symbols incorrectly
3. What will be the output of this Swift code?
func test() {
    defer { print("First") }
    defer { print("Second") }
    print("Inside")
}
test()
medium
A. Inside First Second
B. First Second Inside
C. Inside Second First
D. Second First Inside

Solution

  1. Step 1: Understand defer execution order

    Multiple defer statements run in reverse order of appearance when the function ends.
  2. Step 2: Trace the output

    "Inside" prints first. Then the last defer prints "Second", then the first defer prints "First".
  3. Final Answer:

    Inside Second First -> Option C
  4. Quick Check:

    defer runs last-in-first-out = A [OK]
Hint: Multiple defers run in reverse order at function end [OK]
Common Mistakes:
  • Assuming defers run in order added
  • Thinking defer runs immediately
  • Mixing print order
4. Identify the error in this Swift function using defer:
func cleanup() {
    defer print("Done")
    print("Working")
}
medium
A. Missing braces {} after defer
B. Cannot use print inside defer
C. defer must be last statement
D. No error, code is correct

Solution

  1. Step 1: Check defer syntax

    The defer statement requires a code block enclosed in braces {}.
  2. Step 2: Analyze the given code

    The code uses defer print("Done") without braces, which is invalid syntax.
  3. Final Answer:

    Missing braces {} after defer -> Option A
  4. Quick Check:

    defer needs braces {} for code block = B [OK]
Hint: Always use braces {} after defer keyword [OK]
Common Mistakes:
  • Omitting braces for defer block
  • Thinking defer can take single statement without braces
  • Assuming defer must be last line
5. You want to open a file, write data, and ensure the file is always closed even if an error occurs. Which is the best way to use defer for cleanup in Swift?
hard
A. Open file, write data, then use defer { close file } immediately after opening
B. Write data, then open file, then defer { close file }
C. Use defer { close file } only if no error occurs
D. Close file manually without defer after writing

Solution

  1. Step 1: Understand defer for cleanup

    defer ensures cleanup code runs at function end, even if errors happen.
  2. Step 2: Apply defer after resource acquisition

    Place defer { close file } immediately after opening the file to guarantee closure.
  3. Final Answer:

    Open file, write data, then use defer { close file } immediately after opening -> Option A
  4. Quick Check:

    defer after open ensures cleanup always runs = A [OK]
Hint: Place defer right after resource acquisition for safe cleanup [OK]
Common Mistakes:
  • Placing defer after writing data
  • Skipping defer on errors
  • Closing file manually risking leaks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard