Skip to content

Instantly share code, notes, and snippets.

@Revolucent
Created October 9, 2014 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Revolucent/c45583823e8604ca3eaa to your computer and use it in GitHub Desktop.
Save Revolucent/c45583823e8604ca3eaa to your computer and use it in GitHub Desktop.
Unique Extension Method For Swift SequenceTypes
/*
The reason this does not return a value is that SequenceType
is very general. It has no methods for modifying the sequence,
only traversing it.
Instead, we pass our "unique" method a closure that tells it
how to add a value to our result. The result is not visible
at all to this method. It is captured by our closure.
The reason we don't pass the result as a parameter is because it
has to be declare with var anyway, otherwise it is immutable. I.e.,
something like this won't work:
unique(inputSequence, [Int]()) { $0.append($1) }
The compiler will complain, trust me. (At least as of this writing.)
Lastly, this assumes your module name is Prosumma. Replace
this with your module name, otherwise it won't compile.
*/
public func unique<H: Hashable, S: SequenceType where S.Generator.Element == H>(sequence: S, append: (H) -> Void) -> Void {
var hashMap = [H: Bool]()
for elem in sequence {
let key = hashMap[elem]
if key == nil {
hashMap[elem] = true
append(elem)
}
}
}
extension Array {
public func unique<H: Hashable>() -> [H] {
var result = [H]()
Prosumma.unique(map({ $0 as H })) { result.append($0) }
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment