0
0
Swiftprogramming~20 mins

Capture lists in closures 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
Output of closure capturing a variable
What is the output of this Swift code snippet?
Swift
var x = 10
let closure = { [x] in
    print(x)
}
x = 20
closure()
A10
B20
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
Think about when the value of x is captured by the closure.
Predict Output
intermediate
2:00remaining
Effect of capture list on reference type
What will this Swift code print?
Swift
class Counter {
    var count = 0
}
let counter = Counter()
let closure = { [counter] in
    print(counter.count)
}
counter.count = 5
closure()
A5
BRuntime error
CCompilation error
D0
Attempts:
2 left
💡 Hint
Consider how reference types behave when captured in closures.
🔧 Debug
advanced
3:00remaining
Why does this closure cause a retain cycle?
Examine the code below. Why does it cause a retain cycle?
Swift
class Person {
    var name: String
    lazy var greet: () -> Void = {
        print("Hello, \(self.name)!")
    }
    init(name: String) {
        self.name = name
    }
}
let p = Person(name: "Alice")
p.greet()
AThe closure does not capture self, so no retain cycle occurs.
BThe lazy property causes a syntax error.
CThe closure captures name by value, causing a retain cycle.
DThe closure captures self strongly, causing a retain cycle.
Attempts:
2 left
💡 Hint
Think about how closures capture self by default in classes.
📝 Syntax
advanced
2:00remaining
Correct capture list syntax
Which option shows the correct syntax for capturing a variable weakly in a closure?
Swift
var value = 10
let closure = { /* capture list here */ in
    print(value)
}
A{ [weak var value] in print(value) }
B{ [value weak] in print(value) }
C{ [weak value] in print(value) }
D{ [weak self] in print(value) }
Attempts:
2 left
💡 Hint
The capture list syntax uses square brackets with capture specifiers before the variable name.
🚀 Application
expert
3:00remaining
Predict the output with multiple captures and mutation
What is the output of this Swift code?
Swift
var a = 1
var b = 2
let closure = { [a, b] in
    print("a = \(a), b = \(b)")
}
a = 3
b = 4
closure()
Aa = 3, b = 2
Ba = 1, b = 2
Ca = 1, b = 4
Da = 3, b = 4
Attempts:
2 left
💡 Hint
Captured values are copied at closure creation time.