Understanding Optionals and Exclamation Marks in Swift

November 13, 2015

Swift is a strongly-typed language, meaning all variables must have a defined type. 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

Software development professional with expertise in application architecture, cloud solutions deployment, and financial products development. Possess a Master's degree in Computer Science and an MBA in Finance. Highly skilled in AWS (Certified Solutions Architect, Developer and SysOps Administrator), GCP (Professional Cloud Architect), Microsoft Azure, Kubernetes(CKA, CKAD, CKS, KCNA), and Scrum(PSM, PSPO) methodologies. Happy to connect