Bad practice: testing if a String is empty


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


This code seems pretty harmless, doesn’t it?

But it actually hides quite a serious issue!

So let’s try and understand what that problem is.

The purpose of this code is pretty clear: we’re checking whether or not myString is empty.

As it turns out, Swift also offers a built-in property for this purpose, called isEmpty.

And this second approach is a much better one!

So what’s the difference between the two?

When we call isEmpty, under the hood Swift only needs to check that the string contains at least one character: this is quite fast to execute.

And even better, that execution time doesn’t depend on the length of the string.

On the other hand, the property count works very differently.

count will return the number of visible characters in the string.

And because some unicode characters can be combined into a single visible character, this means that count has to go over all the characters in the string.

So if the string is long, or if there are lots of strings, this code will take a lot of time to execute.

And that’s the big issue behind this code!

So remember, whenever you need to test whether a string is empty, you definitely don’t want to manually test whether its count is greater than zero, because it would be needlessly slow!

That’s all for this article, I hope you’ve enjoyed this new format!

Here’s the code if you want to experiment with it:

if myString.count > 0 {
    // `myString` isn't empty
}

if myString.isEmpty == false {
    // `myString` isn't empty
}
Previous
Previous

When do you really need to use [weak self]? 🤨

Next
Next

Discover CollectionOfOne