Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
removeObject extension for Array in Swift
import Foundation
extension Array {
func indexOfObject(object : AnyObject) -> NSInteger {
return (self as NSArray).indexOfObject(object)
}
mutating func removeObject(object : AnyObject) {
for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object) {
self.removeAtIndex(index)
}
}
}
var a = [3, 3, 1, 2, 3, 3]
a.removeObject(3)
a
@IronLeash

This comment has been minimized.

Copy link

@IronLeash IronLeash commented Feb 16, 2015

There is no need for casting, the following would be also ok

func indexOfObject(object : AnyObject) -> NSInteger {
    return self.indexOfObject(object)
}
@valvoline

This comment has been minimized.

Copy link

@valvoline valvoline commented Jun 14, 2016

what about to use filtering?

import Foundation
extension Array {
    mutating func removeObject<T where T : Equatable>(obj: T) {
        self = self.filter({$0 as? T != obj})
    }

}
@ssferrazza

This comment has been minimized.

Copy link

@ssferrazza ssferrazza commented Jan 7, 2018

@IronLeash I think a casting is necessary here. Omitting it will cause a endless loop.
In Swift 4 it should be something like this:

func indexOfObject(object : AnyObject) -> NSInteger { return (self as NSArray).index(of: object) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment