Array extension to remove object by value

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


        
15条回答
  •  忘了有多久
    2020-11-22 08:36

    You cannot write a method on a generic type that is more restrictive on the template.

    NOTE: as of Swift 2.0, you can now write methods that are more restrictive on the template. If you have upgraded your code to 2.0, see other answers further down for new options to implement this using extensions.

    The reason you get the error 'T' is not convertible to 'T' is that you are actually defining a new T in your method that is not related at all to the original T. If you wanted to use T in your method, you can do so without specifying it on your method.

    The reason that you get the second error 'AnyObject' is not convertible to 'T' is that all possible values for T are not all classes. For an instance to be converted to AnyObject, it must be a class (it cannot be a struct, enum, etc.).

    Your best bet is to make it a function that accepts the array as an argument:

    func removeObject(object: T, inout fromArray array: [T]) {
    }
    

    Or instead of modifying the original array, you can make your method more thread safe and reusable by returning a copy:

    func arrayRemovingObject(object: T, fromArray array: [T]) -> [T] {
    }
    

    As an alternative that I don't recommend, you can have your method fail silently if the type stored in the array cannot be converted to the the methods template (that is equatable). (For clarity, I am using U instead of T for the method's template):

    extension Array {
        mutating func removeObject(object: U) {
            var index: Int?
            for (idx, objectToCompare) in enumerate(self) {
                if let to = objectToCompare as? U {
                    if object == to {
                        index = idx
                    }
                }
            }
    
            if(index != nil) {
                self.removeAtIndex(index!)
            }
        }
    }
    
    var list = [1,2,3]
    list.removeObject(2) // Successfully removes 2 because types matched
    list.removeObject("3") // fails silently to remove anything because the types don't match
    list // [1, 3]
    

    Edit To overcome the silent failure you can return the success as a bool:

    extension Array {
      mutating func removeObject(object: U) -> Bool {
        for (idx, objectToCompare) in self.enumerate() {  //in old swift use enumerate(self) 
          if let to = objectToCompare as? U {
            if object == to {
              self.removeAtIndex(idx)
              return true
            }
          }
        }
        return false
      }
    }
    var list = [1,2,3,2]
    list.removeObject(2)
    list
    list.removeObject(2)
    list
    

提交回复
热议问题