Blog

Swift Tip: Non-Empty Collections

Last week, we wrote about an extension on Optional that we used to deal with either a nil value or an empty string:

extension Optional where Wrapped: Collection {
    var nonEmpty: Wrapped? {
        return self?.isEmpty == true ? nil : self
    }
}

This extension allowed us to handle both the nil and the empty case in one go:

var vatNumber: String?
vatNumber.nonEmpty.map { "Your VAT Number is: \($0)" } ?? "No VAT Number."

Pyry Jahkola sent us a good suggestion on Twitter: instead of adding a nonEmpty property on Optional, why not extend Collection with an optional nonEmpty property? This extension is both simpler and more versatile:

extension Collection {
    var nonEmpty: Self? {
        return isEmpty ? nil : self
    }
}

Using this extension together with optional chaining we can write our previous example like this:

vatNumber?.nonEmpty.map { "Your VAT Number is: \($0)" } ?? "No VAT Number."

Now we can use the same extension on non-optional collection types to substitute a default value, using the nil coalescing operator instead of a ternary operator:

var vatNumber: String = "123"
vatNumber.nonEmpty.map { "Your VAT Number is: \($0)" } ?? "No VAT Number."

Admittedly, the differences between these variants are slight. However, we always like to discover new ways of solving a given problem. πŸ˜€

To support our work, you can subscribe, or give someone a gift.


Stay up-to-date with our newsletter or follow us on Twitter.

Back to the Blog

recent posts