问题描述
我有对象,像这样的数组:
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
任何想法?
推荐答案
你所不掌握的是,阵是一个结构,因此是值类型的。它不能代替被突变的方式类实例可以。因此,你总是会创造幕后的新数组,即使你扩展阵列写一个不同诱变 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.
有因此,在不使用的缺点,也没有失去一般性过滤器
和您关闭状态的逻辑负:
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
是这样的:
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"}
但事实上,这是你的时间一个大胖子的浪费。你什么都不做在这里,过滤器
是不是已经在做。它可能的显示的距离,你是变异 myArr,该
代替 myArr.removeIf
语法,但是你没有;你与另一个数组替换它。事实上,的每个的在循环调用 removeAtIndex
创建另一个数组!所以你还不如用过滤
和快乐。
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.
这篇关于从对象的数组中删除匹配的项目吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!