Hun*_*ter 3 count nsdictionary ios swift
我有一本字典是[uid: true, uid: false, uid: false, uid: false]. 我如何在 Swift 中计算true和false值的数量,以便我可以看到这本字典中有 1true和 3 false?
使用该filter方法删除不需要的值,然后调用count结果即可。
// Get the count of everything which is true
let trueCount = dict.filter { $0.value }.count
// Get the count of everything which is false
let falseCount = dict.filter { !$0.value }.count
// A more efficient way to get the count of everything which is false
let falseCount = dict.count - trueCount
Run Code Online (Sandbox Code Playgroud)
最直接的方法是使用为此目的而设计的结构:计数集。没有原生 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))")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2590 次 |
| 最近记录: |