Object Oriented Programming

Initializer in Swift

An initializer is a special method used to build a class object on initialization (instantiation).

Known as a constructor in other languages.


Syntax
modifier class className {
    init(inputParameters) {
        //set fields and run methods needed on instantiation here
    }
}

Notes

With a method, if the first parameter is declared external, all other parameters are implicitly declared external.

Often times, a constructor's input parameters will have the same variable name as the variables within the class. Member variables within the class can be referenced using the 'self' keyword.


Example
public class City {
    var cityName: String //fields
    var population: Int
    init(cityName: String, population: Int) { //constructor
        self.cityName = cityName
        self.population = population
    }
}

< Access Modifiers   |   Instantiation >

© 2019 SyntaxDB. All Rights Reserved.