Consider the following Swift code. What will be printed?
func makeIncrementer() -> () -> Int { var total = 0 let incrementer: () -> Int = { total += 1 return total } return incrementer } let increment = makeIncrementer() print(increment()) print(increment())
Remember that closures capture variables by reference, so the variable total keeps its value between calls.
The closure incrementer captures the variable total by reference. Each time increment() is called, total increases by 1. So the first call prints 1, the second prints 2.
Choose the best explanation why closures in Swift behave as reference types.
Think about what happens when you assign a closure to multiple variables.
Closures capture variables from their surrounding context and share the same instance when assigned or passed around, so they behave like reference types.
Examine the code below. What error will it produce when compiled?
func createClosure() -> () -> Int { var count = 0 return { count += 1 return count } } let closure1 = createClosure() let closure2 = closure1 closure2 = createClosure()
Look at how closure2 is declared and used.
closure2 is declared with let, so it cannot be assigned a new value after initialization. The line closure2 = createClosure() causes a compile-time error.
What will this Swift code print?
func makeCounter() -> () -> Int { var count = 0 return { count += 1 return count } } let counter1 = makeCounter() let counter2 = counter1 print(counter1()) print(counter2())
Remember closures are reference types and share captured variables.
Both counter1 and counter2 refer to the same closure instance, so the count variable is shared. The first call increments to 1, the second increments to 2.
Given the code below, how many unique closure instances exist after execution?
func createClosure() -> () -> Int { var value = 0 return { value += 1 return value } } let c1 = createClosure() let c2 = createClosure() let c3 = c1 let c4 = c2 let c5 = c1
Closures created by separate calls to createClosure() are unique instances.
Each call to createClosure() creates a new closure instance. c1 and c3 and c5 refer to the same instance, and c2 and c4 refer to another. So there are 2 unique closure instances.