Optional Values in Swift
Are you new to Swift, or coming to Swift from Objective-C? One challenge for new Swift programmers is working with optional values in Swift: "What's with all the question marks?" "Why are there exclamation points all over?" "When do I use a question mark or exclamation mark?" "How do I handle nil?" These are all great and totally legitimate questions.
Briefly put, an optional lets you have a variable that may contain a value, or may be empty (in other words, it is nil). Because Swift is a strongly typed language and requires that each variable and constant contain a valid value respective of its type, the use of optional values in Swift allows you to have variables that may not contain a value at all, as certain circumstances dictate. In this article, we'll discuss optional values: what they really are, their syntax, and when and how to use them.
A Little Background
At first it may seem odd, but to understand optional values, we need to first cover the concept of nil, and some quick basics on enumerations (or just "enums").
Nil
The concept of nil has been around for a long time, and many Objective-C programmers are accustomed to using nil as part of their everyday work. In Objective-C, nil is a pointer to an empty object, and you can use it to your advantage in many ways. Sending messages to nil is acceptable, as it will just stifle the message. In Swift, however, nil is treated slightly differently, as nil is actually the absence of a value, not just a pointer to an empty object. It is strictly nothing. If you access nil at runtime in Swift, your app will crash, which was not always the case with Objective-C.
So if we can't access nil at runtime or else the app would crash, what should we do instead? Hang tight, we'll discuss that in a minute. Let's discuss enumerations next before we get to handling nil with optional values.
Enumerations
Enums are more powerful in Swift than in many other languages, because they don't necessarily need to have a backing value (or raw value); but if they do have raw values, they aren't just tied to integers. Raw values for enums in Swift can be any of the built-in types: Strings, Bools, Characters, and so on—or even any other custom type you want.
Enum-Associated Values
In addition to raw values, enums in Swift can have something called associated values. This means that an enum's case can have a value stored along with it, of whatever type you define. Say you have an enum that has a Success case and a Failure case, and you use this to track the JSON result from a call to a web service. In the event of a successful response, it would be nice to know what the successful data looks like. Likewise, in the event of an error, you may want to inspect the error object. The following example illustrates how this enum would look:
enum Result { case Success(String) case Failure(NSError) }
To get the respective value of either Success or Failure, you would simply use a switch statement to extract the values. If you are unfamiliar with how to do that, keep reading; a video later in this article walks you through this very concept.
Onward to Optionals
By now I'm sure you're asking, "What does all this have to do with optionals?" An optional value is simply an enumeration with two cases: Some and None. The Some case has an associated value of whatever type you give it, represented by a placeholder type named T. The T placeholder type will be replaced at runtime with whatever type you define it to be, or Swift will infer its type from context. Here's a trimmed-down look at the definition of an optional:
enum Optional<T> { case Some(T) case None }
In the event that the optional instance has a value, it is held in the Some case's associated value. If the optional instance is nil (remember, that's the absence of a value), the instance's case is simply None.
Declaring Optional Values
Using the previous definition of optional values, it would stand to reason that if you want an optional value, and it has an actual value (which should be of type String), you would declare your variable as such:
var maybeString: Optional<String>
While this declaration is perfectly acceptable, a shorter way, widely accepted as convention, is to append a question mark (?) after the type in the type parameter list. Rewriting the above example, you could declare your variable like this instead:
var maybeString: String?
What It Means to Be Optional
It helps to think of an optional value as a box: It might contain something—or nothing. In other words, you could think of an optional value as a present you give at a holiday party with your co-workers. There may be a gift inside, represented as Some(Gift), or there may be nothing inside, represented as None, perhaps for the co-worker you don't like. (I wouldn't suggest giving an empty present to your co-workers, as you may quickly earn enemies.)
The most important thing to note about optional values is that when dealing with a variable that's an optional String, for example (String?), the variable's type is not String; it's really Optional<String>, meaning that the optional value is really an enumeration that contains a String (if there is a value). Attempting to do something with the String instance directly, such as convert to all uppercase, is not allowed. The error you will see in Xcode is that the uppercaseString computed property is not defined on Optional, and you may need to unwrap the value first.
How to Get the Value Out of an Optional
In order to obtain the value from an optional value's Some case, you must unwrap it. Unwrapping the value means that you ask the optional value for the associated value inside its Some case. For example, if you're unwrapping the String? instance described earlier, and the Some case has a non–nil-associated value, it would return an actual String instance.
There are many ways to unwrap an optional value, split into two categories: conditional binding, and using operators.
Conditional Binding
Using conditional binding, you can first check whether an optional value has an associated value before unwrapping it. This technique provides safety, and it's clear to the reader of your code that you intend to safely unwrap an optional value for use, or somehow handle its being nil. There are two ways to conditionally bind: using the so-called "if let syntax," and by way of switch statements.
If Let Syntax
With if let syntax, what you're really doing is inserting an assignment inside an if statement. Swift will assign the unwrapped value into the new constant you declare if the operation is possible. If the unwrapping and assignment fails, the if statement's else clause (if provided) is executed, and your app can safely resume execution. Consider the following example of attempting to unwrap an optional Int:
var a: Int? = 5 // a is equal to Some(Int), the stored Int is 5 if let unwrappedA = a { println("I unwrapped a, and it's value is \(unwrappedA).") } else { println("Unwrapping failed") }
Switch Statements
Another way to unwrap optional values is to use switch statements. Since an optional is simply an enum that can equal one of two possible cases, switch statements are a terrific way to get at optional data, while still providing clear intent. Consider the example I just described, using a switch statement to extract the optional data:
var a: Int? = 5 switch a { case .Some (let unwrappedA): println("I unwrapped a, value: \(unwrappedA).") case .None: println("unwrappedA is nil.") }
In the following video, I recap the information discussed above in an Xcode playground. The video starts by creating a Result type with associated values, and then indicates how to show the results of unwrapping optional values using both forms of conditional binding.
Operators
Optional values can also be unwrapped directly in several ways: forcibly with the ! forced unwrap operator, by using the ?? nil coalescing operator, or with a single ? operator before a chaining expression using dot syntax.
Forced Unwrapping
One way to unwrap an optional value is to force the unwrap with the exclamation point (!) operator. While it is easy to just append an exclamation point to the end of an optional value to unwrap it, there are implications to doing so. If the optional value is nil at runtime, you will force your app to crash, which may leave the user bewildered (or never wanting to use your app again). The forced unwrap operator should be used when you're absolutely certain that the optional value is not nil, perhaps after first testing for nil in a conditional statement. Forcibly unwrapping looks like the following example:
var a: Int? = 5 let b = a! // b is equal to 5 and of type Int, not Int?. var c: Int? = nil let d = c! // crash!
Nil Coalescing
Perhaps one of my personal favorite operators in Swift is the nil coalescing operator, by which you can provide a default value to be assigned in the event that unwrapping your optional fails.
The nil coalescing operator, denoted by two question marks together (??), is an infix operator, meaning that it is placed between two operands. The left operand is your optional value, which may be nil or may have a value, and the right operand is a default value that is acceptable to be assigned. Consider this example:
var a: Int? = nil let b = a ?? 42 // b is equal to 42, of type Int, not Int?. var c: Int? = 5 let d = c ?? 0 // d is equal to 5, of type Int, not Int?.
Optional Chaining
The last way to unwrap an optional value is to use optional chaining. This is the same idea of using dot syntax to chain together function calls, or obtaining properties from instances that contain instances that contain instances. Optional chaining is best used when dot syntax is needed to traverse a set of objects, and should not be used when simply accessing an optional value by itself.
To use optional chaining, you insert a question mark (?) operator after the optional value, and then use dot syntax to call another function or obtain another property. Consider an example where you have an optional Person instance, who has an optional Dog instance (because that person may or may not have a dog), and that dog may or may not have fleas, represented as [Flea], an array of Fleas:
let dogHasNoFleas = person?.dog?.fleas?.isEmpty
One thing to note here is that dogHasNoFleas is still an optional value, because the result of optional chaining is always an optional value. The reason for returning an optional is that at any point along the chain, the operation could fail and return nil, so the resulting variable must also be an optional. Optional chaining is often used in conjunction with if let syntax.
Using optional chaining can be confusing sometimes when you wonder where to put the question mark. As a rule, the question mark should go after the item that is optional itself, and before any actions on that optional value. Dictionaries and functions come to mind specifically, because dictionaries use subscripts to access their values, and functions require parentheses to be called. Dictionaries and functions may also be optional. Additionally, items returned from a dictionary subscript call are optional, and a function's return value may also be optional, so depending on why you need to use optional chaining, you may need to put the question mark after the call to a function or dictionary variable name and also the subscript, before any dot syntax for chaining. The following video exercise explains optional chaining, going through examples of using optional chaining with dictionaries and functions.
Another Way to Declare Optional Values
In addition to declaring a standard optional (with the ? character after the type name), you can alternatively declare a variable to be an implicitly unwrapped optional. An implicitly unwrapped optional is still an optional value, but you do not need to do anything special to unwrap its inner value when using it. In other words, you do not need to forcibly unwrap it, use nil coalescing, or insert the ? character when chaining calls; Swift will implicitly unwrap it for you.
However, a big word of caution goes with this method of declaring optionals. You need to make sure that your variable will not be nil when you access it, or else your app will crash at runtime and potentially leave your users with a bad experience.
Implicitly unwrapped optionals are often used when declaring an outlet (with the @IBOutlet declaration). The reason is that the storyboard grabs a reference to the UI element, and your outlet simply creates a weak reference to it. The idea is that since the storyboard owns a reference to it, it will not be nil as long as it is on screen or in the view/navigation stack somewhere.
You can also use implicitly unwrapped optionals when the value of the variable is not known at the time of initialization, but once it is set, it's guaranteed not to be nil. Consider the following example of using an implicitly unwrapped optional text field and accessing its text property:
var textField: UITextField! textField.text = "Hello" // sets "Hello" to the text property textField.text // prints "Hello"
Notice that no special modifier is used when accessing the inner value of an implicitly unwrapped optional; you use it just as you would a non-optional variable. But again caution is warranted: Be entirely sure that your variable is not nil when accessing it, or your app will crash at runtime. The final video discusses implicitly unwrapped optionals, demonstrating how to use them and add safety precautions.
Wrap-Up
I hope you can now see the power that optional values provide, and the inherent value in the way Swift treats optional values. Using optional values can be to your advantage, as long as you know what type you are working with at the time. Whether it's an optional type or a non-optional type, it will help you become more proficient in Swift.
In this article we covered the basics of optional values and discussed what an optional value really is. We covered what nil is in Swift and Objective-C, and also how nil is handled in Swift. We also discovered how optional values in Swift are really just an enum with two cases: Some and None. We covered how to unwrap optional values by using several different methods, including with conditional binding and using operators. Finally, we covered the difference between a standard optional value and an implicitly unwrapped optional value.
I hope you enjoyed this article and the embedded videos. If you'd like to follow me on Twitter, my username is @bjmillerltd, and you can stay tuned to my blog at http://bjmiller.me.