从对象数组中删除匹配的项目? [英] Remove matched item from array of objects?

查看:25
本文介绍了从对象数组中删除匹配的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象数组:

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

但是现在我如何从原始的 myArr 中删除它?我希望 filter.first 可以以某种方式返回索引,以便我可以使用 removeAtIndex.或者更好的是,我想做这样的事情:

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

有什么想法吗?

推荐答案

你没有理解的是 Array 是一个结构体,因此是一种值类型.它不能像类实例那样就地变异.因此,您将始终在幕后创建一个新数组,即使您扩展 Array 以编写一个可变的 removeIf 方法.

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.

因此,使用 filter 和关闭条件的逻辑否定没有缺点也没有丧失一般性:

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" }

例如,你可以这样写removeIf:

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"}

但实际上这是对您时间的极大浪费.您在这里没有做 filter 还没有做的事情.它可能从 myArr.removeIf 语法出现你正在改变 myArr 到位,但你不是;您正在用另一个数组替换它.实际上,在该循环中每次调用removeAtIndex 都会创建另一个数组!所以你不妨使用 filter 并高兴起来.

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.

这篇关于从对象数组中删除匹配的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆