Swift - Unwrapping Optionals Using "?"

Introduction

Consider the following scenario:

var str:String?
var empty = str!.isEmpty

Here, str is an optional String and isEmpty is a property from the String class.

However, the preceding code will crash, as str contains nil , and trying to call the isEmpty property from nil results in a runtime error.

The ! character is saying:

  • I am very confident that str is not nil , so please go ahead and call the isEmpty property.

To prevent the statement from crashing, you should instead use the ? character, as follows:

var str:String?
var empty = str? .isEmpty

The ? character is saying: I am not sure if str is nil.

If it is not nil , please call the isEmpty property; otherwise, ignore it.

Related Topic