# Chapter 8 - Capturing from the enclosing scope

**URL:** <https://forums.kodeco.com/t/chapter-8-capturing-from-the-enclosing-scope/181521>\
**Category:** Swift Apprentice\
**Created:** [December 8, 2022, 5:23pm UTC](https://forums.kodeco.com/t/chapter-8-capturing-from-the-enclosing-scope/181521 "2022-12-08T17:23:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![labramalino](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/labramalino/32/105896_2.png) [@labramalino](https://forums.kodeco.com/u/labramalino)\
**Post date:** [December 8, 2022, 5:23pm UTC](https://forums.kodeco.com/t/chapter-8-capturing-from-the-enclosing-scope/181521/1 "2022-12-08T17:23:08Z")

</div>

Why does this work:

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

```

and this not?

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

```

Thanks

---

<div class="post-metadata">

**Author:** ![labramalino](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/labramalino/32/105896_2.png) [@labramalino](https://forums.kodeco.com/u/labramalino)\
**Post date:** [December 10, 2022, 11:34am UTC](https://forums.kodeco.com/t/chapter-8-capturing-from-the-enclosing-scope/181521/2 "2022-12-10T11:34:53Z")

</div>

> [@labramalino](#):
>
> Why does this work:
> 
> ```auto
> func countingClosure() -> () -> Int {
> var counter = 0
> let incrementCounter: () -> Int = {
> counter += 1
> return counter
> }
> return incrementCounter
> }
> 
> ```
> 
> and this not?
> 
> ```auto
> func countingClosure() -> () -> Int {
> var counter = 0
> let incrementCounter: () -> Int = {
> return counter += 1 // not working
> }
> return incrementCounter
> }
> 
> ```

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.

---

<div class="post-metadata">

**Author:** ![system](https://s3.amazonaws.com/cdn.raywenderlich.com/community/forum-assets/noun-game-ghost-878668.png) [@system](https://forums.kodeco.com/u/system)\
**Post date:** [May 24, 2023, 9:23am UTC](https://forums.kodeco.com/t/chapter-8-capturing-from-the-enclosing-scope/181521/3 "2023-05-24T09:23:23Z")

</div>

Closed on May 24, 2023, 9:23am UTC

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