Home > Articles > Programming > General Programming/Other Languages

Optional Values in Swift

BJ Miller, author of iOS Swift Programming By Example LiveLessons (Video Training), discusses some basics that Swift programmers need to understand, such as the use of nil and special characters when used (carefully) to create optionals that give your code more flexibility.
Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020