I have a dictionary that is [uid: true, uid: false, uid: false, uid: false]. How do I, in Swift, count the number of true and false values so that I can see that there is 1 true and 3 false in this dictionary?
The most straightforward way is to use a construct designed for this purpose: a counted set. There is no native Swift counted set, but you can use NSCountedSet.
A counted set works exactly like a set, but it counts how many times you add an element to it.
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))")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With