Junior — Middle
When passing or creating a closure, is it copied or passed by reference?
sobes.tech AI
Answer from AI
In iOS (Swift/Objective-C), closures are passed by reference, not copied when passed or created. The closure object itself is a reference type.
However, when capturing variables from the external context, a closure may create copies of these values (for example, if they are of struct type), or capture them by reference (if they are classes).
Example in Swift:
var x = 10
let closure = { print(x) } // closure captures x by value (copies)
x = 20
closure() // will print 10, since x was captured by copy
When passing a closure to a function or storing it in a variable, a reference to the closure is passed, not a copy of the entire closure body.
Thus, closures are passed by reference, but captured variables can be copied or captured by reference depending on their type and context.