Remove element from collection during iteration with forEach

前端 未结 3 1604
旧巷少年郎
旧巷少年郎 2020-12-06 09:30

Recently, I wrote this code without thinking about it very much:

myObject.myCollection.forEach { myObject.removeItem($0) }

where myOb

3条回答
  •  情话喂你
    2020-12-06 10:19

    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]
    

提交回复
热议问题