Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove matched item from array of objects?

Tags:

arrays

swift

I have an array of objects like this:

var myArr = [
  MyObject(name: "Abc", description: "Lorem ipsum 1."),
  MyObject(name: "Def", description: "Lorem ipsum 2."),
  MyObject(name: "Xyz", description: "Lorem ipsum 3.")
]

I know I can find the matched item like this:

var temp = myArr.filter { $0.name == "Def" }.first

But now how do I remove it from the original myArr? I was hoping the filter.first can return an index somehow so I can use removeAtIndex. Or better yet, I would like to do something like this:

myArr.removeAll { $0.name == "Def" } // Pseudo

Any ideas?

like image 245
TruMan1 Avatar asked Apr 16 '15 14:04

TruMan1


People also ask

How do you remove one property from an array of objects?

To remove a property from all objects in an array: Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.

How do you remove all duplicates from an array of objects?

To remove the duplicates from an array of objects: Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.


2 Answers

What you are not grasping is that Array is a struct and therefore is a value type. It cannot be mutated in place the way a class instance can be. Thus, you will always be creating a new array behind the scenes, even if you extend Array to write a mutating removeIf method.

There is thus no disadvantage nor loss of generality in using filter and the logical negative of your closure condition:

myArr = myArr.filter { $0.name != "Def" }

For example, you could write removeIf like this:

extension Array {
    mutating func removeIf(closure:(T -> Bool)) {
        for (var ix = self.count - 1; ix >= 0; ix--) {
            if closure(self[ix]) {
                self.removeAtIndex(ix)
            }
        }
    }
}

And you could then use it like this:

myArr.removeIf {$0.name == "Def"}

But in fact this is a big fat waste of your time. You are doing nothing here that filter is not already doing. It may appear from the myArr.removeIf syntax that you are mutating myArr in place, but you are not; you are replacing it with another array. Indeed, every call to removeAtIndex in that loop creates another array! So you might as well use filter and be happy.

like image 189
matt Avatar answered Sep 28 '22 09:09

matt


Apple had added what you want in Swift 4:

var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."
like image 39
Yulong Xiao Avatar answered Sep 28 '22 09:09

Yulong Xiao