iOS engineer who likes clean, simple designs and sans-serif.

Loading

Unwrapping Optional Counts in Swift 3

We are VERY busy converting our Swift 2.2 code to Swift 3.0. I’ve been running into this problem a lot and thought I would share a quick tip (as of Xcode Version 8.0 beta 6).

Before Swift 3, we liked to do a lot of our sanity checks like this

if (collection.products.count > 0) {
  // Do Something
}

Which is just a shorter way of writing this:

if (collection.products != nil && collection.products.count > 0) {
  // Do Something
}

But now with Swift 3, the code above won’t compile.
The Xcode migration tool will change your code to this:

if ((collection.products.count)! > 0) {
  // Do Something
}

YUCK, it’s ugly! And, not to mention, this could cause a lot of crashes.
After evaluating some options, I came up with a clean way to make this code easier on the eyes (and without having to unwrap everything):

if (collection.products.count ?? 0 > 0) {
  // Do Something
}

The ?? operator gives us a way to supply a default value when an optional is nil.

Hope you liked this trick!

Leave a Comment