Chapter 9. Optionals, Unwrapping, Generics, and More: Nothing Optional About It

Note

It’s a funny joke because you can’t really avoid optionals.

image

Dealing with data that doesn’t exist can be challenging. Thankfully, Swift has a solution. Meet optionals. In Swift, an optional allows you to work with a value, or with the absence of a value. They’re one of the many ways that Swift is designed to be a safe language. You’ve occasionally seen optionals in your code so far, and now we’re going to explore them in more depth. Optionals make Swift safe because they keep you from accidentally writing code that would break if it’s missing data, or if something can sometimes return a value that isn’t actually a value.

Optionals Exposed

image

Today’s interview: the humble Optional

Head First: Thanks for joining us, Optional. We’re all very excited to get to know you a bit better.

Optional: No problem at all. I’m very popular these days, but I always make time to talk to people. Do you mind if I make notes about you while we talk?

Head First: About me? I’m talking to you to learn about you! But, I guess, sure. Whatever you need.

Optional: Thanks! What’s your favorite number?

Head First: I don’t really have one. Sorry. I’m told you’re one of Swift’s most powerful features. Care to comment on what ...

Get Head First Swift now with the O’Reilly learning platform.

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