Way back in Bite #1 (zomg!) we talked about initializing View Controllers in Swift. Swift's init functions are still a source of confusion for many newcomers. Today we'll look at a couple cases where Swift synthesizes inits for us.

Structs

Swift offers free "memberwise" initializers for Structs. This means that if we define a Struct, and opt not to define any initializers, one will be synthesized for us, under the hood, using the properties we've given to the Struct. If we add our own though, we lose the synthesized init, and become responsible for defining 100% for the Struct's inits.

struct Spaceship {
  var name: String
}

let ship = Spaceship(name: "Outrider")

Default Initializers

Classes can synthesize a default init function for us. Only one that accepts 0 parameters, though. We'll get this if we define a class, while assigning default values to all its properties:

class Spaceship {
  var topSpeed = 1000
  var currentSpeed = 0
}
let ship = Spaceship()

There's plenty to cover about init'ing things in Swift. We'll take a look in future Bites. Oh, and happy 200th Bite !