Partial application of “mutating” method is not allowed

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store