Skip to content

Instantly share code, notes, and snippets.

@alskipp
Last active August 29, 2015 14:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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"
@alskipp
Copy link
Author

alskipp commented Sep 24, 2014

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] = [:]

@dndydon
Copy link

dndydon commented Sep 25, 2014

sweet!

@kelan
Copy link

kelan commented Jun 14, 2015

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.)

@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