ios - swift:计算字典中的重复值

标签 ios swift count nsdictionary

我有一个字典是[uid: true, uid: false, uid: false, uid: false]。我如何在 Swift 中计算 truefalse 值的数量,以便我可以看到有 1 个 true 和 3 个 false 在这本字典里?

最佳答案

最直接的方法是使用为此目的设计的构造:计数集。没有原生的 Swift 计数集,但您可以使用 NSCountedSet

计数集的工作方式与集合完全相同,但它会计算您向其中添加元素的次数。

let dict = [
    "key1": true,
    "key2": true,
    "key3": false
]

let countedSet = NSCountedSet()
for (_, value) in dict {
    countedSet.add(value)
}
print("Count for true: \(countedSet.count(for: true))")

关于ios - swift:计算字典中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44784482/

相关文章:

mysql - SELECT MAX from COUNT,其他行变量不正确

python - 我如何计算每行中不同的特定字符的出现次数

ios - "error": "InvalidRegistration" while sending push notifications

iOS 错误 : Supported orientations has no common orientation with the application (iPhone)

ios - 框架使用库崩溃

ios - 取消事件的调用

ios - 计算 Twitter 字符数

iOS 应用程序 : Missing 64-bit support

ios - 详细 View UITableView - 在 segue 之前传递数据

MySQL 查询 DISTINCT,COUNT