In one of our last posts we showed you how to make your swift code more sexy with a custom conditional assignment operator. Today, let’s look at another simple and cool improvement of dev’s daily life. It’s going to be about collections, and their well known method isEmpty.

Let’s take a string, as an example, and check whether it’s empty or not.

It’s easy when the string is not optional, but what if we needed to check an optional string? We want to return true for both the empty string as well as for a nil value, don’t we?

By the way… Yes, string is a collection and you don’t have to use foo.count > 0, but I assume we all know that. ?

There are 3 different examples of how to achieve that and I think you can find dozens more, but all of these options have something in common – they’re badly readable, long and last but not least you have to think when you’re writing it and devs don’t like to think more than necessary. ?

It would be great to check an optional string like this…

It is possible! All we need is to remember that Optional is enum, with two cases – some and none. ☝️ So we can create an extension on Optional where the type is Collection and implement new isEmpty method.

Now you can check collections’ emptiness like a boss. ? Just directly copy-paste this snippet to your code or use our ACKategories, this and lot of other useful tricks are part of it, you will love it. ❤️

Leave a Reply

Your email address will not be published. Required fields are marked *