Topics

Topics

Way back in Bite #1 (zomg!) we talked about initializing View Controllers in Swift. Swift'sinitfunctions are still a source of confusion for many newcomers. Today we'll look at a couple cases where Swiftsynthesizesinits 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'sinits.

structSpaceship{varname:String}letship=Spaceship(name:"Outrider")

Default Initializers

Classes can synthesize a default initfunction 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:

classSpaceship{vartopSpeed=1000varcurrentSpeed=0}

letship=Spaceship()

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