Array extension to remove object by value

前端 未结 15 1249
我在风中等你
我在风中等你 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

    There is another possibility of removing an item from an array without having possible unsafe usage, as the generic type of the object to remove cannot be the same as the type of the array. Using optionals is also not the perfect way to go as they are very slow. You could therefore use a closure like it is already used when sorting an array for example.

    //removes the first item that is equal to the specified element
    mutating func removeFirst(element: Element, equality: (Element, Element) -> Bool) -> Bool {
        for (index, item) in enumerate(self) {
            if equality(item, element) {
                self.removeAtIndex(index)
                return true
            }
        }
        return false
    }
    

    When you extend the Array class with this function you can remove elements by doing the following:

    var array = ["Apple", "Banana", "Strawberry"]
    array.removeFirst("Banana") { $0 == $1 } //Banana is now removed
    

    However you could even remove an element only if it has the same memory address (only for classes conforming to AnyObject protocol, of course):

    let date1 = NSDate()
    let date2 = NSDate()
    var array = [date1, date2]
    array.removeFirst(NSDate()) { $0 === $1 } //won't do anything
    array.removeFirst(date1) { $0 === $1 } //array now contains only 'date2'
    

    The good thing is, that you can specify the parameter to compare. For example when you have an array of arrays, you can specify the equality closure as { $0.count == $1.count } and the first array having the same size as the one to remove is removed from the array.

    You could even shorten the function call by having the function as mutating func removeFirst(equality: (Element) -> Bool) -> Bool, then replace the if-evaluation with equality(item) and call the function by array.removeFirst({ $0 == "Banana" }) for example.

提交回复
热议问题