Tricky output-based questions on Closures — Part II

Janvi Arora
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 be 3 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 the message variable.
  • When the closure is executed inside performOperation, it prints the captured value of message.
  • 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 be 4 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 the result variable directly.
  • closure2 captures result as a constant at the time of its creation.
  • When closure1 is called, it modifies result to 10.
  • When closure2 is called, it prints the captured value of result, which is 0 because it was captured before closure1 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 be 4 because it's the value that completes the loop.
  • So, the output will be: 16, 16, 16.

--

--

No responses yet