According to The Apple Swift documentation: Global functions are closures that have a name and do not capture any values. But I ran into an example domenstrating use of closures in the book IOS 11 Programming Fundamentals with Swift, which passes a global function A as a parameter into another global function B to modify the value of a global variable x. The book states that A captures X, which contradicts what the Swift documentation says.
The code example:
func pass100(_ f: (Int) -> ()) {
f(100)
}
var x = 0
print(x) // output 0
func setX(newX: Int) {
x = newX
}
pass100(setX)
print(x) //output 100
The above code snippet works in Xcode and I am confused. Could anyone explain what's going on here?
This is what "capturing" means:
A closure can capture constants and variables from the surrounding context in which it is defined. The closure can then refer to and modify the values of those constants and variables from within its body, even if the original scope that defined the constants and variables no longer exists.
Global functions are said to not capture anything because you can never leave the global scope while your program is running, so there is no point in capturing anything. If it did capture something, that means global variables can still be changed even after you somehow "left" the global scope (maybe the program finishes running), which would be weird.
The global function in your code is not capturing anything. It can change the value of x simply because x is still in scope. You've not left the global scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With