Swift Initialization
Initialization is the preparation process for using an instance of a class, structure, or enumeration. This process includes setting an initial value for each property in the instance and performing the necessary preparation and initialization tasks.\n\nSwift initializers use the init() method.\n\nUnlike initializers in Objective-C, Swift initializers do not need to return a value. Their main task is to ensure that the new instance is correctly initialized before its first use.\n\nClass instances can also define a deinitializer to perform memory cleanup before the class instance is deallocated.\n\n* * *\n\n## Initial Assignment for Stored Properties\n\nClasses and structures must set appropriate initial values for all stored properties when an instance is created.\n\nWhen a stored property is assigned a value in an initializer, its value is set directly, and no property observers are triggered.\n\nThe assignment process for stored properties in an initializer:\n\n* Create an initial value.\n\n* Specify a default property value in the property definition.\n\n* Initialize the instance and call the init() method.\n\n* * *\n\n## Initializers\n\nInitializers are called when creating a new instance of a specific type. Its simplest form is similar to an instance method without any parameters, named with the keyword init.\n\n### Syntax\n\ninit(){ // Code to be executed after instantiation}\n### Instance\n\nThe following structure defines an initializer init without parameters, and initializes the stored properties length and breadth to 6 and 12:\n\nstruct rectangle { var length: Double var breadth: Double init() { length = 6 breadth = 12 }}var area = rectangle()print("rectangle Area is \\(area.length*area.breadth)")\nThe output of the above program execution is:\n\nrectangle Area is 72.0\n\n* * *\n\n## Default Property Values\n\nWe can set initial values for stored properties in an initializer; similarly, we can also set default values for them when declaring the property.\n\n> Using default values can make your initializer more concise and clear, and the type of the property can be automatically inferred from the default value.\n\nIn the following instance, we set default values when declaring the properties:\n\nstruct rectangle {// Set default value var length = 6 var breadth = 12}var area = rectangle()print("rectangle's Area is \\(area.length*area.breadth)")\nThe output of the above program execution is:\n\nrectangle Area is 72\n\n* * *\n\n## Initialization Parameters\n\nYou can provide initialization parameters when defining the initializer init(), as shown below:\n\nstruct Rectangle { var length: Double var breadth: Double var area: Double init(fromLength length: Double, fromBreadth breadth: Double) { self.length = length self.breadth = breadth area = length * breadth } init(fromLeng leng: Double, fromBread bread: Double) { self.length = leng self.breadth = bread area = leng * bread }}let ar = Rectangle(fromLength: 6, fromBreadth: 12)print("Area is: \\(ar.area)")let are = Rectangle(fromLeng: 36, fromBread: 12)print("Area is: \\(are.area)")\nThe output of the above program execution is:\n\nArea is: 72.0Area is: 432.0\n\n* * *\n\n## Internal and External Parameter Names\n\nLike function and method parameters, initialization parameters also have an internal parameter name used inside the initializer and an external parameter name used when calling the initializer.\n\nHowever, initializers do not have an identifiable name before the parentheses like functions and methods do. Therefore, when calling an initializer, the initializer to be called is mainly determined by the parameter names and types in the initializer.\n\nIf you do not provide an external name for the parameter when defining the initializer, Swift will automatically generate an external name identical to the internal name for each initializer's parameter.\n\nstruct Color { let red, green, blue: Double init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } init(white: Double) { red = white green = white blue = white }}// Create a new Color instance, pass values through the external parameter names for three colors, and call the constructor let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)print("red Value is: \\(magenta.red)")print("green Value is: \\(magenta.green)")print("blue Value is: \\(magenta.blue)")// Create a new Color instance, pass values through the external parameter names for three colors, and call the constructor let halfGray = Color(white: 0.5)print("red Value is: \\(halfGray.red)")print("green Value is: \\(halfGray.green)")print("blue Value is: \\(halfGray.blue)")\nThe output of the above program execution is:\n\nred Value is: 1.0 green Value is: 0.0 blue Value is: 1.0 red Value is: 0.5 green Value is: 0.5 blue Value is: 0.5\n### Parameters Without External Names\n\nIf you do not want to provide an external name for a parameter of an initializer, you can use an underscore `_` to explicitly describe its external name.\n\nstruct Rectangle { var length: Double init(frombreadth breadth: Double) { length = breadth * 10 } init(frombre bre: Double) { length = bre * 30 } //No external name for init(_ area: Double) { length = area }}// Call without providing an external name let rectarea = Rectangle(180.0)print("Area is: \\(rectarea.length)")// Call without providing an external name let rearea = Rectangle(370.0)print("Area is: \\(rearea.length)")// Call without providing an external name let recarea = Rectangle(110.0)print("Area is: \\(recarea.length)")\nThe output of the above program execution is:\n\nArea is: 180.0Area is: 370.0Area is: 110.0\n\n* * *\n\n## Optional Property Types\n\nIf a custom type contains a stored property that logically allows a nil value, you need to define it as an optional type.\n\nWhen a stored property is declared as optional, it will automatically be initialized to nil.\n\nstruct Rectangle { var length: Double? init(frombreadth breadth: Double) { length = breadth * 10 } init(frombre bre: Double) { length = bre * 30 } init(_ area: Double) { length = area }}let rectarea = Rectangle(180.0)print("Area is:\\(rectarea.length)")let rearea = Rectangle(370.0)print("Area is:\\(rearea.length)")let recarea = Rectangle(110.0)print("Area is:\\(recarea.length)")\nThe output of the above program execution is:\n\nArea is:Optional(180.0)Area is:Optional(370.0)Area is:Optional(110.0)\n\n* * *\n\n## Modifying Constant Properties During Initialization\n\nAs long as the value of a constant can be determined before the initialization process ends, you can modify the value of a constant property at any point during the initialization process.\n\nFor a class instance, its constant properties can only be modified during the initialization process of the class that defines it; they cannot be modified in a subclass.\n\nEven though the length property is now a constant, we can still set its value in the class's initializer:\n\nstruct Rectangle { let length: Double? init(frombreadth breadth: Double) { length = breadth * 10 } init(frombre bre: Double) { length = bre * 30 } init(_ area: Double) { length = area }}let rectarea = Rectangle(180.0)print("Area is:\\(rectarea.length)")let rearea = Rectangle(370.0)print("Area is:\\(rearea.length)")let recarea = Rectangle(110.0)print("Area is:\\(recarea.length)")\nThe output of the above program execution is:\n\nArea is:Optional(180.0)Area is:Optional(370.0)Area is:Optional(110.0)\n\n* * *\n\n## Default Initializer\n\nThe default initializer will simply create an instance where all property values are set to their defaults:\n\nIn the following instance, all properties in the ShoppingListItem class have default values, and it is a base class with no parent class. It will automatically acquire a default initializer that can set default values for all properties.\n\nclass ShoppingListItem { var name: String? var quantity = 1 var purchased = false}var item = ShoppingListItem()print("Name is: \\(item.name)")print("Numeric value is: \\(item.quantity)")print("Is payment made: \\(item.purchased)")\nThe output of the above program execution is:\n\nName is: nilNumeric value is: 1Is payment made: false\n### Memberwise Initializers for Structure Types\n\nIf a structure provides default values for all its stored properties and does not provide any custom initializers, it can automatically acquire a memberwise initializer.\n\nWhen calling a memberwise initializer, we pass values through parameter names identical to the member property names to complete the initial assignment of the member properties.\n\nIn the following example, a structure Rectangle is defined, which contains two properties, length and breadth. Swift can automatically infer their type as Double based on the initial assignments of 100.0 and 200.0 for these two properties.\n\nstruct Rectangle { var length = 100.0, breadth = 200.0}let area = Rectangle(length: 24.0, breadth: 32.0)print("Rectangle area: \\(area.length)")print("Rectangle area: \\(area.breadth)")\nSince both stored properties have default values, the Rectangle structure automatically acquires a memberwise initializer init(width:height:). You can use it to create new instances of Rectangle.\n\nThe output of the above program execution is:\n\nRectangle area: 24.0Rectangle area: 32
YouTip