1

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?

Fattie
  • 27,874
  • 70
  • 431
  • 719

2 Answers2

3

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")
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270
1

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")
}
Sixten Otto
  • 14,816
  • 3
  • 48
  • 60