Tricky output-based questions on Closures — Part II
2 min readMay 1, 2024
var closures: [() -> Void] = []
for i in 0..<3 {
closures.append {
print(i)
}
}
closures[0]()
closures[1]()
closures[2]()
Output Explanation:
- This code snippet creates an array of closures that each print the current value of
i
. - However, since
i
is captured by reference in the closures, they all share the same value. - At the time the closures are executed, the value of
i
will be3
because it's the value that completes the loop. - So, the output will be:
3
,3
,3
.
func performOperation(_ operation: () -> Void) {
print("Before operation")
operation()
print("After operation")
}
func createClosure() -> () -> Void {
let message = "Inside closure"
return {
print(message)
}
}
let closure = createClosure()
performOperation(closure)
Output Explanation:
- The
createClosure
function returns a closure that captures and prints themessage
variable. - When the closure is executed inside
performOperation
, it prints the captured value ofmessage
. - So, the output will be:
Before operation
Inside closure
After operation
var closures: [() -> Void] = []
for i in 1...3 {
closures.append { print(i) }
}
closures.forEach { $0() }
Output Explanation:
- This code snippet creates an array of closures that each print the current value of
i
. - Since
i
is captured by reference in the closures, they all share the same value. - At the time the closures are executed, the value of
i
will be4
because it's the value that completes the loop. - So, the output will be:
4
,4
,4
.
var result = 0
let closure1 = { result += 10 }
let closure2 = { [result] in print(result) }
closure1()
closure2()
Output Explanation:
closure1
modifies theresult
variable directly.closure2
capturesresult
as a constant at the time of its creation.- When
closure1
is called, it modifiesresult
to10
. - When
closure2
is called, it prints the captured value ofresult
, which is0
because it was captured beforeclosure1
executed. - So, the output will be:
0
.
var functions: [() -> Void] = []
for i in 1...3 {
functions.append { print(i * i) }
}
functions.forEach { $0() }
Output Explanation:
- This code snippet creates an array of closures that each print the square of the current value of
i
. - Since
i
is captured by reference in the closures, they all share the same value. - At the time the closures are executed, the value of
i
will be4
because it's the value that completes the loop. - So, the output will be:
16
,16
,16
.