Skip to content

Instantly share code, notes, and snippets.

@alskipp
Last active August 29, 2015 14:06
Show Gist options
  • Save alskipp/5f4672d4126c61938ba0 to your computer and use it in GitHub Desktop.
Save alskipp/5f4672d4126c61938ba0 to your computer and use it in GitHub Desktop.
Generic uniq function in Swift
// uniq func for Swift 1.2
func uniq<C: ExtensibleCollectionType where C.Generator.Element: Hashable>(collection: C) -> C {
var seen:Set<C.Generator.Element> = Set()
return reduce(collection, C()) { result, item in
if seen.contains(item) {
return result
}
seen.insert(item)
return result + [item]
}
}
uniq([1, 2, 2, 2, 3, 4, 4]) // > [1, 2, 3, 4]
uniq("aaabccc") // > "abc"
// uniq func for Swift 1.1
func uniq<C: ExtensibleCollectionType where C.Generator.Element: Hashable>(collection: C) -> C {
var seen: [C.Generator.Element: Void] = [:]
return reduce(collection, C()) { result, item in
if seen[item] != nil {
return result
}
seen[item] = ()
return result + [item]
}
}
uniq([1, 2, 2, 2, 3, 4, 4]) // > [1, 2, 3, 4]
uniq("aaabccc") // > "abc"
@kelan
Copy link

kelan commented Jul 25, 2015

I updated it for Xcode 7 beta 4, and wrote about it here: http://kelan.io/2015/collection-extensions-in-swift-uniq-and-tapdescription/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment