1

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)

err-1: enter image description here

err-2: enter image description here :

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]
iKK
  • 6,394
  • 10
  • 58
  • 131
  • 1
    Your constraint should be `where Element: Comparable & Hashable` and your return value + counts dictionary should be `[Element: Int]` – dan Oct 17 '18 at 22:26
  • Apart from the compilation errors, I don't think your algorithm will work. Lucky for you, there are lots of good implementations of this algorithm. See https://stackoverflow.com/q/30545518/3141234 – Alexander Oct 17 '18 at 22:26
  • Thank you, dan, for the excellent answer. With your help, my algo works perfectly fine now. – iKK Oct 18 '18 at 17:05

0 Answers0