concept initializer in category swift

appears as: The initializer, initializer, initializers, initializer, n initializer, initializers
Swift in Depth

This is an excerpt from Manning's book Swift in Depth.

The initializer from ImageType returns an optional. An optional initializer indicates that it can fail. When the initializer does fail—when you give it an unusable string—the initializer returns a nil value. Don’t worry if this isn’t clear yet; you’ll handle optionals in depth in chapter 4.

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.

The BoardGame superclass has three initializers: one designated initializer and two convenience initializers to make initialization easier (see figure 5.1).

Figure 5.1. BoardGame initializers

Before continuing, get acquainted with the two types of initializers for classes.

Listing 5.9. Initializing BoardGame
//Convenience initializer
let boardGame = BoardGame(names: ["Melissa", "SuperJeff", "Dave"])

let players = [
    Player(name: "Melissa"),
    Player(name: "SuperJeff"),
    Player(name: "Dave")
]

//Convenience initializer
let boardGame = BoardGame(players: players)

//Designated initializer
let boardGame = BoardGame(players: players, numberOfTiles: 32)

You witnessed how Swift has many types of initializers, each one paired with its own rules and oddities. You noticed how initializers are even more complicated when you’re subclassing. Subclassing may not be popular, yet it can be a viable alternative depending on your background, coding style, and the code that you may inherit when joining an exciting company.

Hello Swift!: iOS app programming for kids and other beginners

This is an excerpt from Manning's book Hello Swift!: iOS app programming for kids and other beginners.

  • What are initializers?