Swift expression, empty or nonexistent dictionary in array - reliably zero?

107 Views Asked by At

A String dictionary of arrays

blah: [String:[Stuff]]

For a given key, say "foo", I want to know how many items are in that array - but, if there is no such array, I just want to get zero.

I'm doing this ...

blah["foo"]?.count ?? 0

so

if ( (blah.down["foo"]?.count ?? 0) > 0) {
   print("some foos exist!!")
else {
   print("there are profoundly no foos")
}

Am I correct?

2

There are 2 best solutions below

0
On BEST ANSWER

You are correct but you might find it easier to remove the optional earlier:

(blah["foo"] ?? []).count 

or

if let array = blah.down["foo"], !array.isEmpty {
   print("some foos exist!!")
} else {
   print("there are profoundly no foos")
}
0
On

Yes. But I'd probably write it with optional binding, like:

if let c = blah.down["foo"]?.count, c > 0 {
   print("some foos exist!!")
}
else {
   print("there are profoundly no foos")
}