Playing with Collection Extension in Swift 4.2, I try to do the following:
If a collection contains duplicates, then I would like to get the number of each element in the Collection.
See my code below.
There are two errors (see screenshots)
Here is my code :
extension Collection where Iterator.Element: Comparable {
func occurrencesOfElements() -> [Int: Self] {
var counts: [Int: Self] = [:]
let sortedArr = self.sorted(by: { $0 > $1 })
let uniqueArr = Set(sortedArr) // err-1 !!!!!!!!
if uniqueArr.count < sortedArr.count {
uniqueArr.forEach { counts[$0, default: 0] += 1 } // err-2 !!!!!!!
}
return counts
}
}
// Testing with...
[6, 7, 4, 5, 6, 0, 6].occurrencesOfElements()
// Expected result (see number 6 occurs twice) :
// [0 : 1, 4: 1, 5: 1, 6 : 2, 7 : 1]