Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift: count recurring values in a dictionary

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?

like image 587
Hunter Avatar asked Jan 21 '26 12:01

Hunter


1 Answers

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))")
like image 146
deadbeef Avatar answered Jan 24 '26 00:01

deadbeef