Skip to content

Instantly share code, notes, and snippets.

@enzosterro
Last active September 21, 2017 09:10
Show Gist options
  • Save enzosterro/0247f2636d8eee06dcaa1cc0cc15c30c to your computer and use it in GitHub Desktop.
Save enzosterro/0247f2636d8eee06dcaa1cc0cc15c30c to your computer and use it in GitHub Desktop.
Extension to Count Unique Elements in Array
extension Array where Element: Comparable {
var uniqueElements: Int {
let sorted = self.sorted(by: <)
let initial: (Element?, Int) = (.none, 0)
let counter = sorted.reduce(initial) { ($1, $0.0 == $1 ? $0.1 : $0.1 + 1) }
return counter.1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment