Understanding Optional and Exclamation Mark in Swift

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!

Originally published at victorleungtw.com on November 13, 2015.

By Victor Leung

Experience in software development, consulting services and technical product management. Understanding of business and technology with an MBA in Finance and a Master degree in Computer Science. AWS Certified Solution Architect with experience in building products from scratch and serving as a charismatic leader.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: