Removing object from array in Swift 3

前端 未结 13 2047
余生分开走
余生分开走 2020-12-08 12:49

In my application I added one object in array when select cell and unselect and remove object when re-select cell. I used that code but give me error.

extens         


        
相关标签:
13条回答
  • 2020-12-08 13:26

    Another nice and useful solution is to create this kind of extension:

    extension Array where Element: Equatable {
    
        @discardableResult mutating func remove(object: Element) -> Bool {
            if let index = index(of: object) {
                self.remove(at: index)
                return true
            }
            return false
        }
    
        @discardableResult mutating func remove(where predicate: (Array.Iterator.Element) -> Bool) -> Bool {
            if let index = self.index(where: { (element) -> Bool in
                return predicate(element)
            }) {
                self.remove(at: index)
                return true
            }
            return false
        }
    
    }
    

    In this way, if you have your array with custom objects:

    let obj1 = MyObject(id: 1)
    let obj2 = MyObject(id: 2)
    var array: [MyObject] = [obj1, obj2]
    
    array.remove(where: { (obj) -> Bool in
        return obj.id == 1
    })
    // OR
    array.remove(object: obj2) 
    
    0 讨论(0)
提交回复
热议问题