2

The description comes from the swift office document

Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables.

I don't fully understand the store references part. Does it means It creates some sort of "Pointer" to a variable? If the value changed the "de-referenced pointer" also changed to the new value. I think Swift has no pointer concept. I borrowed it to express my understandings.

Would be very nice that someone can provide a simple code lines to explain how the closure stores reference to the constants/variables.

SLN
  • 4,772
  • 2
  • 38
  • 79
  • 1
    If you carry on reading that section in the Swift language guide, you'll see they show & explain an example of a `makeIncrementer` function that demonstrates how closures capture values as references. The `runningTotal` variable is captured as a reference, allowing multiple invocations of the returned function (that captures the `runningTotal`) to increment it, as it has a reference to that variable – even though it's a value type. – Hamish Jun 21 '16 at 18:24
  • 2
    Note that even if Swift as a language had no pointers in it (JavaScript has closures but no raw-memory pointers for instance), that would have no impact on the assembly that the Swift complier outputs. There are going to be many indirect references ("pointers") in the assembly code. Many things that are illegal in "Swift" are totally legal in the swiftc output (unbounded gotos for instance are commonplace in the compiler output, but do not exist in the language). – Rob Napier Jun 21 '16 at 18:46

1 Answers1

3

Does it means It creates some sort of "Pointer" to a variable? If the value changed the "de-referenced pointer" also changed to the new value.

Yes.

I think Swift has no pointer concept.

It most certainly does, in the (implicit) form of reference types (classes), and the (explicit) form of UnsafePointer

Here's an example of a variable being captured in a closure. This all happens to be single threaded, but you could have this closure be dispatched by grand central dispatch. x is captured so that it exists for the entire life of the closure, even if the closure exists after x's declaring scope (f()) exits.

func f() {
    var x = 0 //captured variable

    _ = {
       x = 5 //captures x from parent scope, and modifies it
    }()

    print(x) //prints 5, as x was modified by the closure
}

f()

I wrote another answer that explains the relationships between functions, closures, and other terms. It's worth reading, IMO.

Community
  • 1
  • 1
Alexander
  • 59,041
  • 12
  • 98
  • 151