我有一个 CGPoint
数组,
pointArray = [(532.7, 150.0), (66.6, 150.0), (129.2, 150.0), (129.2, 150.0), (301.2, 150.0), (444.2, 150.0), (532.7, 150.0), (532.7, 150.0), (532.7, 150.0)]
如何获取每个点重复的次数?
最佳答案
正如@Alexander 在评论中所说,您应该使用 NSCountedSet
,您可以像这样使用它:
let array = [
CGPoint(x: 532.7, y: 150.0),
CGPoint(x: 66.6, y: 150.0),
CGPoint(x: 129.2, y: 150.0),
CGPoint(x: 129.2, y: 150.0),
CGPoint(x: 301.2, y: 150.0),
CGPoint(x: 444.2, y: 150.0),
CGPoint(x: 532.7, y: 150.0),
CGPoint(x: 532.7, y: 150.0),
CGPoint(x: 532.7, y: 150.0)
]
let countedSet = NSCountedSet(array: array)
countedSet.count(for: array.last!) //returns 4
如果您不想使用 NSCountedSet
,您可以将字典中的每个点存储为键,将计数存储为值。棘手的是 CGPoint
不符合 Hashable
,你可以这样做:
extension CGPoint:Hashable{
public var hashValue: Int {
let x = Double(self.x)
let y = Double(self.y)
return Int(((x + y)*(x + y + 1)/2) + y)
//this hash function may not be the best for your data
}
}
var map = [CGPoint:Int]()
for point in array {
if let count = map[point] {
map[point] = count + 1
} else {
map[point] = 1
}
}
map[array.last!]//returns 4
我认为最好使用 NSCountedSet
关于arrays - 如何获取 CGPoint 数组的每个值重复的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41867645/