Partial application of “mutating” method is not allowed

The PM Booth
1 min readMar 1, 2021

--

I came across this error recently and figured I am not the only one who was wondering about this.

// Error[1, 2, 3, 4].forEach(foo.add)// Works[1, 2, 3, 4].forEach { foo.add($0) }

Explanation

  • In the error-case Swift tries to mutate `foo` directly by reassigning a copy of it with the given value. This is a problem since the closure scope does *not* hold a copy of `foo` and is therefore tied to the original `foo`.
  • The original struct falling out of scope would become an issue for the closure
  • Swift then seems to assume that the closure is `escaping` even though it is not
  • In the working-case Swift creates a copy of `foo` for the scope of the closure, mutates that copy and reassigns that copy to `foo`.
  • Since the closure holds a copy of the original struct, it falling out of scope is not an issue

Kudos to:

https://stackoverflow.com/questions/37488316/partial-application-of-mutating-method-is-not-allowed

--

--