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

时间:2017-01-24 13:19:43

标签: arrays sorting swift3 mapping

我看到this post 其中显示了如何以下列方式获得数组的最常值:例如,整数:

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")
}

我想为CGPoints数组获得相同的结果,这有点不同。我尝试使用相同的代码并收到错误:

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

var counts = [CGPoint: Int]()

和错误

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

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

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

1 个答案:

答案 0 :(得分:0)

这一行错误意味着什么:

  

键入&#39; CGPoint&#39;不符合协议&#39; Hashable&#39;

是你不能使用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") 
}