I am trying to write a simple Array extension that provides a \'distinct\' method. Here is what I have so far:
extension Array {
func distinct() -> T[]
Finally found out how to do it:
extension Array {
func contains(obj: T) -> Bool {
return self.filter({$0 as? T == obj}).count > 0
}
func distinct(_: T) -> T[] {
var rtn = T[]()
for x in self {
if !rtn.contains(x as T) {
rtn += x as T
}
}
return rtn
}
}
And usage/testing:
let a = [ 0, 1, 2, 3, 4, 5, 6, 1, 2, 3 ]
a.contains(0)
a.contains(99)
a.distinct(0)
Unfortunately, I can't figure out a way to do it without having to specify an argument which is subsequently ignored. The only reason it's there is to invoke the correct form of distinct. The major advantage of this approach for distinct seems to be that it's not dumping a common term like distinct into the global namespace. For the contains case it does seem more natural.