0
0
Swiftprogramming~20 mins

Capturing values from context in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Closure Capture 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 closure capturing example?

Consider this Swift code where a closure captures a variable from its context. What will be printed?

Swift
var count = 0
let incrementer = { count += 1; print(count) }
incrementer()
incrementer()
print(count)
A2\n2\n2
B1\n1\n0
C0\n1\n2
D1\n2\n2
Attempts:
2 left
💡 Hint

Closures capture variables by reference, so changes inside affect the original variable.

Predict Output
intermediate
1:30remaining
What does this Swift closure print when capturing a constant?

Look at this Swift code where a closure captures a constant. What will be printed?

Swift
let number = 5
let printNumber = { print(number) }
printNumber()
ACompilation error
B0
C5
Dnil
Attempts:
2 left
💡 Hint

Constants can be captured by closures and used inside them.

🔧 Debug
advanced
2:30remaining
Why does this Swift closure capture cause unexpected output?

Examine this Swift code where a closure captures a loop variable. Why does it print the same number multiple times?

Swift
var closures: [() -> Void] = []
for i in 1...3 {
    closures.append { print(i) }
}
closures.forEach { $0() }
AAll closures capture the same variable <code>i</code> by reference, so they print the final value 4.
BEach closure captures a different copy of <code>i</code>, so they print 1, 2, 3 respectively.
CThe closures print 1, 1, 1 because <code>i</code> is reset each loop.
DThe code causes a runtime error because <code>i</code> is out of scope.
Attempts:
2 left
💡 Hint

Think about how Swift captures loop variables in closures.

Predict Output
advanced
1:30remaining
What is the output of this Swift closure with capture list?

What will this Swift code print? It uses a capture list to capture a variable by value.

Swift
var value = 10
let closure = { [value] in print(value) }
value = 20
closure()
A10
BCompilation error
C20
Dnil
Attempts:
2 left
💡 Hint

Capture lists let you capture a variable's value at the time the closure is created.

🧠 Conceptual
expert
2:00remaining
Which statement about Swift closure captures is true?

Choose the correct statement about how Swift closures capture values from their context.

AClosures always capture variables by value, so changes outside do not affect the closure.
BClosures capture variables by reference by default, but capture lists can force capture by value.
CClosures cannot capture constants from their surrounding context.
DCapturing variables in closures always causes a memory leak.
Attempts:
2 left
💡 Hint

Think about how capture lists affect variable capturing.