Skip to content

Instantly share code, notes, and snippets.

@bfernandesbfs
Last active November 11, 2016 18:57
Show Gist options
  • Save bfernandesbfs/0ace376521f93c026e859da75fe312e9 to your computer and use it in GitHub Desktop.
Save bfernandesbfs/0ace376521f93c026e859da75fe312e9 to your computer and use it in GitHub Desktop.
func unique<S: Sequence, E: Hashable>(_ source: S) -> [E] where E==S.Iterator.Element {
var seen: [E:Bool] = [:]
return source.filter { seen.updateValue(true, forKey: $0) == nil }
}
let a = ["four","one", "two", "one", "three","four", "four"]
print(unique(a))
struct Person {
var name: String
var age: Int
}
extension Person: Hashable {
var hashValue: Int {
get {
return name.hashValue ^ age.hashValue
}
}
static func ==(l: Person, r: Person) -> Bool {
return l.hashValue == r.hashValue
}
}
let p = [Person(name: "Jack", age: 22),
Person(name: "Anne", age: 26),
Person(name: "Mary", age: 27),
Person(name: "Anne", age: 26)]
print(unique(p))
p.contains(Person(name: "Bruno", age: 22))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment