Lightning Read #2: Optional String Pitfalls
0 minutes reading
Photo by Max Bender on Unsplash

I was trying to build a URL the other day. Check the following code block:

Seems legit, right?

Assume that we’re passing 23940 as userId to this initializer. Depending on the Swift version, path value would be:

Subtle, but heart-breaking.

Firstly, beware of this issue if you’re working on a super-old project which still uses Swift 2.x for some reason, and planning to migrate.

Secondly, we could use a guard-let instead of a guard-check statement here to fix this issue. However, it’s not convenient to have guard statements everywhere, especially when you simply want to print stuff.

I created the following struct to overcome this problem:

Note: Yes, we could also print “nil” instead of “(null)” but I think the latter is more expressive. You can always choose this one or the other.

Whenever you have optionals, you simply wrap them in a Printable struct as below.

Or, in a more complex example:

Without Printable struct, these objects would print below;

With Printable, it prints;

The latter seems much cleaner.

Moral of the Story

Don’t use optionals directly while treating them as strings, or printing them on the console.

Thanks for dropping by! And, as usual, help spread the word. ❤️👏

Göksel Köksal

iOS developer. Serious gamer.

Leave a reply