extension Array where Element: Hashable {
func mergeDuplicates() -> [Element: Int] {
var result = [Element: Int]()
self.forEach({ result[$0] = result[$0] ?? 0 + 1 })
return result
}
}
var test = [1,2,3,4,5,6,7,8,5,9,3,3,9,9,9]
let testCount = test.mergeDuplicates()
print(testCount)
The code above provides an extension to any Array type that holds Hashable elements (anything else is not eligible to be the key of a dictionary). Method mergeDuplicates produces the dictionary you want. In its implementation, forEach() executes a closure over every element in the array (this is typically more straightforward and transparent alternative to old-fashioned for-loop). Then on each iteration we check whether there is already existing value in the dictionary with a running count (and use nil-coalescing operator ?? to handle cases when a particular value was not yet met before, hence it's zero). Then increment, and store (back) into the dictionary.