Recently, I wrote this code without thinking about it very much:
myObject.myCollection.forEach { myObject.removeItem($0) }
where myOb
I asked a similar question in the Apple Developer Forum and the answer is "yes, because of the value semantics of Array".
@originaluser2 said that already, but I would argue slightly different:
When myObject.removeItem($0) is called, a new array is created and
stored under the name myObject, but the array that forEach() was called upon is not modified.
Here is a simpler example demonstrating the effect:
extension Array {
func printMe() {
print(self)
}
}
var a = [1, 2, 3]
let pm = a.printMe // The instance method as a closure.
a.removeAll() // Modify the variable `a`.
pm() // Calls the method on the value that it was created with.
// Output: [1, 2, 3]