在Swift中,从数组中删除对象的更好方法是什么?
var testArray:[SomeObject]
let willRemoveObj:SomeObject
...
testArray = testArray.filter({ $0 != willRemoveObj })
或者
guard let index = testArray.indexOf(willRemoveObj) else {
return
}
testArray.removeAtIndex(index)
在Foundation中没有方便的方法,但我们可以使用所需的方法扩展数组结构。请考虑以下内容:
extension Array where Element: Equatable {
mutating func remove(object: Element) {
if let index = index(of: object) {
remove(at: index)
}
}
}
var testArray: Array<Int> = [1, 2]
let toBeRemoved: Int = 1
testArray.remove(object: toBeRemoved)
testArray
func remove(at index: Int) -> Element
函数,“否则,如果第一个参数构成语法短语,则省略其标签”规则适用于mutating func remove(_ object: Element)
函数。 :) - 0x5f3759dfmutating func remove(_ member: Element)
函数也遵循我所描述的“Swift API 设计准则”。remove(at index: Int)
和 remove(_ member: Element)
之间的区别在于前者移除索引处的元素,后者则移除成员。话虽如此,我认为你的观点应该比我的更重要!感谢你的时间,非常感激 : ) - 0x5f3759df
willRemoveObj
相等的所有对象还是仅删除第一个(或仅有的)对象。 - Martin R