Chapter 4. Making optionals second nature
This chapter covers
- Best practices related to optionals
- Handling multiple optionals with guards
- Properly dealing with optional strings versus empty strings
- Juggling various optionals at once
- Falling back to default values using the nil-coalescing operator
- Simplifying optional enums
- Dealing with optional Booleans in multiple ways
- Digging deep into values with optional chaining
- Force unwrapping guidelines
- Taming implicitly unwrapped optionals
This chapter helps you acquire many tools to take you from optional frustration to optional nirvana while applying best practices along the way. Optionals are so pervasive in Swift that we spend some extra pages on them to leave no stone unturned. Even if you are adept at handling optionals, go through this chapter and fill in any knowledge gaps.
The chapter starts with what optionals are and how Swift helps you by adding syntactic sugar. Then we go over style tips paired with bite-sized examples that you regularly encounter in Swift. After that, you’ll see how to stop optionals from propagating inside a method via a guard. We also cover how to decide on returning empty strings versus optional strings. Next, we show how to get more granular control over multiple optionals by pattern matching on them. Then, you’ll see that you can fall back on default values with the help of the nil-coalescing operator.