Memberwise initializer

let region : String

var population: Int{
        print("The population has changed to \(population) from \(oldPopulation)")
var numberOfStoplights: Int
init (region: String, population: Int, stoplights: Int){
    self.region = region
    self.population = population
    numberOfStoplights = stoplights

Is the init(region:population:stoplights:) method here a memberwise initializer? And why we need to initialize twice here? I thought “let region : String”, “var population: Int” and “var numberOfStoplights: Int” these three lines already provided default memberwise initializers, am I wrong? thanks


You really should read the section Initialization in [The Swift Programming Language] ( first.


@emilyman region, population, and numberOfStoplights are not initialized in the code above. This is what the initializer (init(region:population:stoplights:) aims to do.

If you had the above, but provided no initializer, you’d get an error telling you that you either need a) default/initial values for your properties, or b) to define an initializer that gives values to all of the class’s properties.