Created
June 12, 2014 23:12
-
-
Save ankushg/5c3fb3fb21cb1463875b to your computer and use it in GitHub Desktop.
removeObject extension for Array in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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})
}
}
@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
There is no need for casting, the following would be also ok