Last active
August 29, 2015 14:06
-
-
Save alskipp/5f4672d4126c61938ba0 to your computer and use it in GitHub Desktop.
Generic uniq function 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
// 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" |
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
// 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" |
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
This is working for me in Swift 2, using a protocol extension:
then
(Note that the
String
usage changed, because it's no longerCollectionType
in Swift 2.)