我有一个包含多个值(双打)的数组,其中许多都是重复的。我想返回或打印所有唯一值的列表,以及给定值在数组中出现的次数。我对Swift很新,我尝试过几种不同的东西,但我不确定实现这一目标的最佳方法。
这样的事情: [65.0,65.0,65.0,55.5,55.5,30.25,30.25,27.5]
会打印(例如): “3分在65.0分,2分在55.5分,2分在30.25分,1分在27.5分。”
我并不像实现这一目标的方法那样关注输出。
谢谢!
答案 0 :(得分:3)
正如@rmaddy已经评论过,您可以使用Foundation NSCountedSet,如下所示:
import Foundation // or iOS UIKit or macOS Cocoa
let values = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
let countedSet = NSCountedSet(array: values)
print(countedSet.count(for: 65.0)) // 3
for value in countedSet.allObjects {
print("Element:", value, "count:", countedSet.count(for: value))
}
您还可以扩展NSCountedSet以返回元组或字典数组:
extension NSCountedSet {
var occurences: [(object: Any, count: Int)] {
return allObjects.map { ($0, count(for: $0))}
}
var dictionary: [AnyHashable: Int] {
return allObjects.reduce(into: [AnyHashable: Int](), {
guard let key = $1 as? AnyHashable else { return }
$0[key] = count(for: key)
})
}
}
let values = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
let countedSet = NSCountedSet(array: values)
for (key, value) in countedSet.dictionary {
print("Element:", key, "count:", value)
}
这将打印
Element: 27.5 count: 1
Element: 30.25 count: 2
Element: 55.5 count: 2
Element: 65 count: 3
答案 1 :(得分:1)
您可以枚举数组并将值添加到字典中。
var array: [CGFloat] = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
var dictionary = [CGFloat: Int]()
for item in array {
dictionary[item] = dictionary[item] ?? 0 + 1
}
print(dictionary)
或者你可以在阵列上做foreach:
array.forEach { (item) in
dictionary[item] = dictionary[item] ?? 0 + 1
}
print(dictionary)
或@rmaddy说:
var set: NSCountedSet = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
var dictionary = [Float: Int]()
set.forEach { (item) in
dictionary[item as! Float] = set.count(for: item)
}
print(dictionary)