Array extension to remove object by value

前端 未结 15 1043
我在风中等你
我在风中等你 2020-11-22 08:30
extension Array {
    func removeObject(object: T) {
        var index = find(self, object)
        self.removeAtIndex(index)
    }
}
         


        
15条回答
  •  囚心锁ツ
    2020-11-22 08:39

    No need to extend:

    var ra = [7, 2, 5, 5, 4, 5, 3, 4, 2]
    
    print(ra)                           // [7, 2, 5, 5, 4, 5, 3, 4, 2]
    
    ra.removeAll(where: { $0 == 5 })
    
    print(ra)                           // [7, 2, 4, 3, 4, 2]
    
    if let i = ra.firstIndex(of: 4) {
        ra.remove(at: i)
    }
    
    print(ra)                           // [7, 2, 3, 4, 2]
    
    if let j = ra.lastIndex(of: 2) {
        ra.remove(at: j)
    }
    
    print(ra)                           // [7, 2, 3, 4]
    

提交回复
热议问题