Pete On Software

RSS Feed

An Introduction to Swift Optionals

Swift OptionalsIf you are anything like me, the concept of Swift Optionals can be a little confusing. At first blush, it seems fine, but then the way that you have to work with them can leave you scratching your head.

The idea is simple. Swift Optionals are essentially nullable/nillable types from other languages. Obviously, reference types can always be null or nil (depending on the language), but value types cannot. In most (if not all) languages that I am familiar with, you cannot have a null integer or a null boolean. You used to have to be left with creating some logic or understanding that if an Id column was 0 or -1, that meant that it had never been set. Or, you had to never fully rely on a boolean’s false value. It could mean no one had ever set some conditional, or it could mean they had “chosen” and they had chosen “no” or “off”.

In C#, they implemented nullable types to solve this problem. I have an example below of using nullable types. You’ll note that you can actually declare them two ways. Like many things in modern languages, there is the “defined” way and the “shorthand” way. There are a few things I want you to note. First, before you use it, you should check and see if it has a value by consulting its “HasValue” property. But, how could you do that if it is null? It isn’t actually null. The nullable type is actually a container. You are asking the container if anything is inside. The other thing to note is that when I want to use it, .Net infers the call to id.Value for instance. I left it as implicit for id and explicit for otherId so you can see the difference.

If I had called .Value on id while it was set to null, I would have gotten an error that said “Nullable object must have a value”. That’s why you must check.

So, how does this relate to Swift? The syntax is actually very similar to C#’s. I use the question mark to denote that I’ve declared an optional variable. However, if I try to use it like C# and just print it out, I get something that can be confusing. Take a look at this code:

Here is what is output, “Optional(7)”. Unlike C#, it didn’t just auto-unwrap and show 7. It is showing you visibly that that 7 is “wrapped inside an Optional”. That is because – like C# – the ? is “syntactic sugar”. What you are really declaring is this:

Now it is really no wonder why we see “Optional(7)” as the output. Swift is literally just giving us back what is there. What if you wanted to unwrap it, then? To unwrap it, you use the ! symbol, like this:

That will actually output “7” to your console. But, what will this code do?

If I try to force unwrap a nil value, I get this error, “fatal error: unexpectedly found nil while unwrapping an Optional value”. Bad news. One way that you often see this dealt with is like this:

In our case, this code prints “That was nil”. If you change the first line to var id: Int? = 7, it will now output “Id unwrapped is 7”. But… why? This syntax makes use of a few things. First, nil evaluates as false in Swift. Secondly, the “if let” is special syntax to Swift. The variable is only unwrapped in this way in an “if let” scenario. And “if let” only works if you have an Optional being assigned.

For instance, I can’t do either of these:

The compiler errors on both items say, “initializer for conditional binding must have Optional type, not ‘Int'”.

So, “if let” is what you have to work with if you want to check variables and do something different in execution if they are not there. However, you have other options. What if you are handed an Optional, but you just want to work with a “sensible default”? You can stick with “if let” if that makes sense to you. That would look like this:

Another option is to skip the “else” entirely and just preset your variable to what the default should be. If the Optional variable has a value, it will just be overwritten. The previous code and this code both print out “0” to the console.

What if you would like to be a little more concise? You do have the option of using the Swift coalesce operator, ??. That would reduce the previous example to something like this:

That’s all there is to Optionals at their core. In another post, I’ll revisit Optionals and see how you can use them in iOS applications to deal with controls and casts. If you have any questions, let me know.

Leave a Comment