5

KEEPING YOUR PROGRAMS SAFE WITH OPTIONALS

In this chapter, we’ll cover a very cool feature in Swift: optionals. Optionals are variables that can either have a value or no value at all. Swift is different from many programming languages because normal constants and variables must have a value. This makes Swift a safe language because it prevents your code from failing when a variable is expected to have a value but one hasn’t yet been set.

However, there will be times when you need to create a variable but don’t have a value for it yet. In these cases, you can use an optional.

WHAT IS AN OPTIONAL?

You can think of an optional as a box that either ...

Get Coding iPhone Apps for Kids, 1st Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.