如何按照最常见的点排列CGPoint阵列

Hil*_*404 6 arrays sorting mapping swift3

我看到这篇帖子 展示了如何通过以下方式获得数组的最常值:

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")
}
Run Code Online (Sandbox Code Playgroud)

我想为一个数组实现相同的结果CGPoints,这有点不同.我尝试使用相同的代码并得到一个错误:

Type 'CGPoint' does not conform to protocol 'Hashable'
Run Code Online (Sandbox Code Playgroud)

在线

var counts = [CGPoint: Int]()
Run Code Online (Sandbox Code Playgroud)

和一个错误

Value of type 'CGPoint' has no member '1'
Run Code Online (Sandbox Code Playgroud)

在线

if let (value, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) {
Run Code Online (Sandbox Code Playgroud)

如何按照频率和打印顺序排列CGPoint阵列,这是一个具有值和它出现的时间的元组?

小智 1

这行错误意味着什么:

类型“CGPoint”不符合协议“Hashable”

是你不能使用CGPoint对象作为字典的键。

评论中提到的解决方法 Leo Dabus 应该可以很好地工作:使用对象String的调试描述 ( )CGPoint作为 字典的键counts

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") 
}
Run Code Online (Sandbox Code Playgroud)