我看到这篇帖子 展示了如何通过以下方式获得数组的最常值:
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阵列,这是一个具有值和它出现的时间的元组?