How to organize a CGPoint array in order of the most common points

I saw this post which showed how to get the most frequent value of an array, for example, integers as follows:

let myArray = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2] // Create dictionary to map value to count var counts = [Int: Int]() // Count the values with using forEach myArray.forEach { counts[$0] = (counts[$0] ?? 0) + 1 } // Find the most frequent value and its count with max(isOrderedBefore:) if let (value, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) { print("\(value) occurs \(count) times") } 

I want to achieve the same result for an array of CGPoints , this is a little different. I tried using the same code and got an error:

 Type 'CGPoint' does not conform to protocol 'Hashable' 

in line

 var counts = [CGPoint: Int]() 

and mistake

 Value of type 'CGPoint' has no member '1' 

in line

 if let (value, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) { 

How can I arrange a CGPoint array in frequency and print order, say a tuple with the value and the amount of time it appears?

+6
source share
1 answer

What does this error line mean:

Type 'CGPoint' does not conform to the 'Hashable' protocol

is that you cannot use CGPoint objects as keys to a dictionary.

The Leo Dabus workaround mentioned in the comments should work well: use the debug description ( String ) of your CGPoint objects as keys for the counts dictionary:

 var counts = [String: Int]() myArray.forEach { counts[$0.debugDescription] = (counts[$0.debugDescription] ?? 0) + 1 } if let (value, count) = counts.max(by: {$0.value < $1.value}) { print("\(value) occurs \(count) times") } 
0
source

Source: https://habr.com/ru/post/1014368/


All Articles