Chapter 5. Demystifying initializers
This chapter covers
- Demystifying Swift’s initializer rules
- Understanding quirks of struct initializers
- Understanding complex initializer rules when subclassing
- How to keep the number of initializers low when subclassing
- When and how to work with required initializers
As a Swift developer, initializing your classes and structs are one of the core fundamentals that you have been using.
But initializers in Swift are not intuitive. Swift offers memberwise initializers, custom initializers, designated initializers, convenience initializers, required initializers, and I didn’t even mention the optional initializers, failable initializers, and throwing initializers. Frankly, it can get bewildering sometimes.
This chapter sheds some light on the situation so that instead of having a boxing match with the compiler, you can make the most out of initializing structs, classes, and subclasses.
In this chapter, we model a boardgame hierarchy that you’ll compose out of structs and classes. While building this hierarchy, you’ll experience the joy of Swift’s strange initializer rules and how you can deal with them. Since creating game mechanics is a topic for a book itself, we only focus on the initializer fundamentals in this chapter.