Understanding Optionals and Exclamation Marks in Swift

November 13, 2015

Swift is a strongly-typed language, meaning all variables must have a defined type.

2015 11 14

In Swift, there is a special type called "Optional," which can have only one of two possible values:

  1. A value that is not set, meaning it has never been set, or someone has explicitly set it to an unset state, i.e., to the value nil.
  2. A value that is set to something specific.

For example:

    var something = display.text

What is the type of something? We didn’t specify the type of this variable, but Swift can infer it from the context. It sets something to be the same type as display.text. Let's say display.text is of type String; then something will be an Optional String, which means it's an Optional that can contain a String.

How can you extract a string from an Optional? You can "unwrap" the Optional, meaning you inspect it and retrieve the associated value, using an exclamation mark:

    var something = display.text!

Now, the type of something is String, not an Optional. Note that if the value of display.text is nil, your program will crash!

Profile picture

Victor Leung, who blog about business, technology and personal development. Happy to connect on LinkedIn