删除 swift 数组中对象的更好方法是什么

What is the better way to remove object in swift Array

从 Swift 中的数组中删除对象的更好方法是什么?

var testArray:[SomeObject]
let willRemoveObj:SomeObject
...

testArray = testArray.filter({ [=11=] != willRemoveObj })

guard let index = testArray.indexOf(willRemoveObj) else {
  return
}
testArray.removeAtIndex(index)

基金会没有方便的方法。但是我们可以根据需要扩展 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]