O'Reilly logo

Learning Swift™ Programming by Jacob Schatz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required