swiftswift3optional-variables

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


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?


Solution

  • 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")
    }