Last active
September 21, 2017 09:10
-
-
Save enzosterro/0247f2636d8eee06dcaa1cc0cc15c30c to your computer and use it in GitHub Desktop.
Extension to Count Unique Elements in Array
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
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