Swift Optionals, Safety vs Conciseness

If there is one error that everybody, including beginner programmers, are familiar with, it is null pointer exception. Swift tries to protect its programmers from this dreaded exception by adding features that help us realize these errors during compile time. This feature also helps us to think carefully about the state of our variables while we code.

Optionals in Swift are an exciting feature and one of the decisions we would always have to make while using optionals is deciding between safety and conciseness of the code. Every program has variables that needn’t always have a value. For e.g. Lets say I had a program that took a user’s name as input and converted the name to all upper case on pressing “Uppercase” button.

Now the user decides to press the “Uppercase” button without entering her name. This would technically result in a null pointer exception because we are trying to convert a non existent string to upper case. To help us realize that name can potentially be nil, Swift shows compiler error stating that name is not initialized. In order to get around with the compiler error, I have to declare the name variable as “Optional” i.e. the question mark at the end of variable type, indicating that name could be nil.

The above line basically changes the type of name from String to an optional variant of String i.e. “ String?” forcing us to unwrap the value in String? and safely access the String value.

The above piece of code would let us read the String value from String? and also ensures that the uppercaseString method is never called on a nil String and in turn protects us from null pointer exceptions. While the above protects from the exception, it is also quite verbose considering we are just reading a value.

Lets say I decide to call everybody who do not enter their name, “Mary”. The initialization would be:

Now, I am pretty confident that that there is always a value in name variable. In this particular case, I could force unwrap the optional.

The problem with forced unwrapping is that it depends on my confidence level of a value being in name variable. What if I am only 99% percent confident? There is still a chance of ending up with a runtime exception. Also, every single time I refer name variable in my code, I would have to force unwrap it with a “!”

In order to make it even more concise i.e. not use “if unwrapping” or forced unwrapping with “!” every where in the code, we could implicitly unwrap name as follows

Implicitly unwrapping would throw all the safety Swift provides us out of the window because it is highly likely that we might even forget that name is an optional and could potentially be nil.

There is one final way of unwrapping optionals – Optional Chaining. Optional chaining wouldn’t throw a null pointer exception when the name variable is nil but instead just returns nil when uppercaseString method is invoked on name.

We could also show the user a message indicating she didn’t to enter a value.

Yes, it’s a bit verbose because we have to use “?” along with the variable but we don’t have to use “If” clauses to unwrap.

As you can see there is no one way of doing things here. Using optionals and the way to unwrap them really depends on the particular situation and our preferences of safety and concise code.