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.

4.1. The purpose of optionals

4.2. Clean optional unwrapping

4.3. Variable shadowing

4.4. When optionals are prohibited

4.5. Returning optional strings

4.6. Granular control over optionals

4.7. Falling back when an optional is nil

4.8. Simplifying optional enums

4.9. Chaining optionals

4.10. Constraining optional Booleans

4.11. Force unwrapping guidelines

4.12. Taming implicitly unwrapped optionals

4.13. Closing thoughts

Summary

Answers