在Swift中从数组中删除对象的更好方法是什么?
var testArray:[SomeObject]
let willRemoveObj:SomeObject
...
testArray = testArray.filter({ $0 != willRemoveObj })
或
guard let index = testArray.indexOf(willRemoveObj) else {
return
}
testArray.removeAtIndex(index)
答案 0 :(得分:5)
基金会没有方便的方法。但是我们可以用所需的扩展Array结构。考虑一下:
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
结果
[2]