Victor Leung
Victor Leung
BlogAI SolutionAlphaAlgoFlower shopFX CombineIEESushi ClassifierWealth Agile

Understanding Optional and Exclamation Mark in Swift

November 13, 2015

Swift is very strongly typed. All variables have a type. There is a type in Swift called optional. Optional can have only two values:

  1. One value is not set, such as never been set or someone has set it to be not set state, i.e. unset it, to the value nil.
  2. The other value is something, it’s set to something.

For example:

    var something = display.text

What type is “something”? We didn’t specify the type of this variable. Swift can infer the type from the context. It makes “something” to be the same type of display.text. Lets say “display.text” is a type of string, then “something” is an optional string, which is an optional that can be a string.

How to get a string from an optional? You can unwrap the optional, meaning you look in there and get the associated value, with an exclamation mark.

    var something = display.text!

Now the type of “something” is a string, not an optional anymore. Note that if display.text value is nil, then your program is gonna crash!


About Victor Leung

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
LinkedIn
Github
Twitter
@victorleungtw

Continuous improvement

Copyright © victorleungtw.com 2023.