Chapter 8 - Capturing from the enclosing scope

Why does this work:

func countingClosure() -> () -> Int {
  var counter = 0
  let incrementCounter: () -> Int = {
    counter += 1
    return counter
  }
  return incrementCounter
}

and this not?

func countingClosure() -> () -> Int {
    var counter = 0
    let incrementCounter: () -> Int = {
        return counter += 1 // not working
    }
    return incrementCounter
}

Thanks

In the first example, the countingClosure function works because it returns a closure that directly modifies the value of counter by incrementing it by 1. In the second example, the countingClosure function does not work because the expression return counter += 1 attempts to modify the value of counter and return it at the same time. In Swift, it is not possible to modify a value and return it at the same time, which is why the expression in the closure fails.

This topic was automatically closed after 166 days. New replies are no longer allowed.