SLN SLN - 2 months ago 10
Swift Question

Why this is not counted as a closure capture?


Global functions are closures that have name and do not capture any values.


In swift a function is a spatial form of closure. The different is the function has a name and if it is an global function it cannot capture constants and variables from the surrounding context.

However, I found that the global function can also capture the constants and variables from the surrounding context also (please see the sample code below)

let referenceInt = 10

func addOne () -> Int {
return referenceInt + 1 //captured the constant referenceInt
}

let fooA = addOne
let fooB = addOne
let fooC = addOne

print(fooA()) //prints 11
print(fooB()) //prints 11
print(fooC()) //prints 11, (func addOne captured referenceInt ?)

print(referenceInt) //prints 10


Problems:

I believe I didn't fully understand the following concepts:


  1. Simply define a function in playground (like addOne() -> Int here) may not means it is a global function

  2. Having the wrong understanding of the "Capture" for this cases, this is not a capture at all, (but why?)



Helps I'm looking for:

I would be very appreciate you could point out which part I understand wrongly and would be even great that you can give me some explanation.

Thanks

PS:

This question might be a duplication of this one, however, I still post it since there is no clean answer on it yet and my question pushed the question a bit further. However, if you still want to close it, I respect that and I willing to learn from you.

Answer

First, I would question your premise. A closure is a closure. All functions in Swift are closures, and they all capture in just the same way.

Second, I don't see what your code has to do with capturing or closures. You are not doing anything in your code that tests whether anything is being captured. The assignment of the type let fooA = addOne doesn't do anything interesting, and the code inside addOne doesn't do anything interesting either. You are merely adding two values at the time the code runs. Certainly the code inside addOne is permitted to refer to the global variable referenceInt, but that is merely because it is in scope. You aren't doing anything here that elicits that special powers of a closure.

Comments