Archive

Testing for an empty string is a pretty common use case. Swift makes it easy with the isEmpty computed property, which the API docs tell us returns “true iff self contains no characters”. That is, if self == “”.

But it’s also pretty common to expand the definition of “empty” to include nil. In Swift, a value that may be nil is modeled as an Optional, but unfortunately, the Optional type is an enum wrapping its value, so it doesn’t include an isEmpty property. So, testing Optional strings means you have to unwrap. You could use let binding:

var optionalString: String?
// Do some work
if let s = optionalString where s != "" {
// s is not empty or nil
}

Or slightly more succinctly, use the nil coalescing operator “??”:

if !(optionalString ?? "").isEmpty {
// optionalString is not empty or nil
}

But really, we’d like to just use isEmpty directly on our Optional String—it just feels more Swifty:

What we’d really like to do is define an extension on Optional. However, Swift won’t allow that (at least not yet). Trying to declare the extension directly on the generic results in this compiler error:

Fair enough, let’s put our String requirement in a where clause. We can look at the public API in Xcode to see that Optional’s associated type is called Wrapped, so let’s see if we can require Wrapped to be a String:

Note the switch for unwrapping the value: remember that Swift optionals are just enums! That lets us use a very efficient switch statement to access the optional’s associated value and call its isEmpty property.

And then we’re on a roll. We can extend this to other Swift standard library types that already have an isEmpty property simply by declaring that the Wrapped type conforms to IsEmptyTestable: