Skip to content

Instantly share code, notes, and snippets.

@ankushg
Created June 12, 2014 23:12
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ankushg/5c3fb3fb21cb1463875b to your computer and use it in GitHub Desktop.
Save ankushg/5c3fb3fb21cb1463875b to your computer and use it in GitHub Desktop.
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
Copy link

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

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

@valvoline
Copy link

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
Copy link

@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