Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

swift - Remove matched item from array of objects?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...