Array extension to remove object by value

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


        
15条回答
  •  不思量自难忘°
    2020-11-22 08:30

    Implementation in Swift 2:

    extension Array {
      mutating func removeObject(object: T) -> Bool {
        var index: Int?
        for (idx, objectToCompare) in self.enumerate() {
          if let toCompare = objectToCompare as? T {
            if toCompare == object {
              index = idx
              break
            }
          }
        }
        if(index != nil) {
          self.removeAtIndex(index!)
          return true
        } else {
          return false
        }
      }
    }
    

提交回复
热议问题