Optionals: A Gift to Unwrap

Optionals are a unique feature of Swift, and they are used absolutely everywhere. Optionals take a little getting used to but in the end they are a clever feature that helps you achieve clean-looking code with fewer lines while also being stricter.

In many languages, you need to check objects to see whether they are nil or null. Usually, you write some pseudo-code that looks like the following. In this example we check for not null in Javascript:

if(something != null) {...

Not having to write that ugly code all over the place saves you time. In Swift, an optional value contains either a value or nil to indicate that the value is missing. To mark something as optional, you just include a ? next to the type of the object. ...

Get Learning Swift™ Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.