Swift - Get value from Optionals

Introduction

When you have an optional variable, you can unwrap it to get at its value.

You do this using the ! character.

If you unwrap an optional variable and it has no value, your program will throw a runtime error and crash:

// Optional types must be unwrapped using  ! 
anOptionalInteger = 2 
1 + anOptionalInteger! // 3 
anOptionalInteger = nil 
// 1 + anOptionalInteger! 
// CRASH: anOptionalInteger = nil, can't use nil data 

To avoid unwrapping your optional variables, declare a variable as an implicitly unwrapped optional:

var implicitlyUnwrappedOptionalInteger  : Int! 
implicitlyUnwrappedOptionalInteger = 1 
print(1 + implicitlyUnwrappedOptionalInteger) // 2 

Implicitly unwrapped optionals are regular optionals.

They can either contain nil, or not.

Whenever you access their values, the compiler unwraps them.

Related Topic