我看到了这篇文章,它展示了如何以以下方式获取数组中最常见的值,例如整数:
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数组,并打印出一个元组,其中包含值和出现次数?
CGPoint(x:0.1 + 0.2,y:0)
与CGPoint(x:0.3,y:0)
是不同的。 - Martin Rvar 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) 出现了 \(count) 次") }
https://gist.github.com/leodabus/b109b2ca9633c44974399a771690fe1d - Leo Dabus