Memberwise initializer


#1
let region : String

var population: Int{
    didSet(oldPopulation){
        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


#2

You really should read the section Initialization in [The Swift Programming Language] (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097-CH3-ID0) first.


#3

@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.