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" |
sweet!
This is working for me in Swift 2, using a protocol extension:
extension ExtensibleCollectionType where Self.Generator.Element: Hashable {
func uniq() -> Self {
var seen:Set<Self.Generator.Element> = Set()
return reduce(Self()) { result, item in
if seen.contains(item) {
return result
}
seen.insert(item)
return result + [item]
}
}
}
then
print([1, 2, 2, 2, 3, 4, 4].uniq()) // > [1, 2, 3, 4]
print(String("aaabccc".characters.uniq())) // > "abc"
(Note that the String
usage changed, because it's no longer CollectionType
in Swift 2.)
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
With thanks to https://twitter.com/brentdax for the correct dictionary declaration incantation.
var seen: [C.Generator.Element: Void]()
doesn't work. The following does:var seen: [C.Generator.Element: Void] = [:]