Swift - Data Type Optional Types

Introduction

Optional Types is like Int?.

The ? character indicates that this variable can optionally contain a value:nil.

You can use the If statement to determine whether num does indeed contain a value.

If it does, you need to use the ! character after the variable name to use its value, like this:

Demo

let str = "125"
let num = str.toInt ()
if num != nil {/*from w ww.  java  2s  .  c o  m*/
   let multiply = num! * 2
   print(multiply)   //250
}

Here num is an Optional Type.

The ! character indicates that you know that the variable contains a value and you indeed know what you are doing.

The use of the ! character is known as forced unwrapping of an optional's value .

Here, num is an optional due to type inference.

To explicitly declare a variable as an optional type, you can append the ? character to the type name.

For example, the following statement declares description to be an optional string type:

var description: String?

You can assign a string to description :

description = "Hello"

You can also assign the special value nil to an optional type:

description = nil

You cannot assign nil to a non-optional type.

Related Topic