In this tutorial you will learn about the Swift Initialization and its application with practical example.
Swift Initialization
When an instance of a class, structure, or enumeration is created it must be provided with some initial values before it is ready to be used. Instance initialization is the process which involves setting up initial value for instance property and to perform any required task to make instance ready to use.
- Swift Initialization
- Swift Initializer Syntax
- Swift Initialization with Parameters
- Swift Initialization with Multiple Initializers
- Swift Initializer with Parameter Names and Argument Labels
- Initializer Parameters Without Argument Labels
- Swift Optional Property Types
- Default Initializers
- Swift Initializer Delegation for Value Types
- Initializer Inheritance and Overriding
- Swift Failable Initializer
- The init! Failable Initializer
- Required Initializers
In swift, we have special method called initializers that can take care of whole initialization process. Initializers are invoked automatically when an instance of a particular is created. The Initializers ensure that new instances of a type created is correctly initialized before they are used for the first time.
In swift, an intializer can be created by implementing init() method with zero more parameters, initializers does not mean to return any value.
Swift Initializer Syntax
Syntax:-
Following is the simplest form of an initializer, an instance method with no parameters is created with the init keyword.
1 2 3 |
init() { //Initialization stuff come here } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Circle{ var radius:Double = 3 var area:Double init() { area = 3.14 * radius * radius } func getArea() -> Double{ return area } } var c = Circle() var result = c.getArea() print("W3Adda - Swift Initialiazer") print("Area of circle is: \(result)") |
Here, we have defined a class with two(radius and area) properties and defined a initializer init() method. For radius we have assigned initial value during its declaration and we have calculated area value in initializer init() method, and there is instance method getArea return area value when invoked.
When you run above swift program you will see the following output –
Output:-
Swift Initialization with Parameters
In swift, an intializer init() method is allowed to accept zero more parameters. An intializer init() method with zero more parameters can be defined as following –
Syntax:-
1 2 3 |
init(parameterList) { //Initialization stuff come here } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Rectangle{ var height:Int var width:Int var area:Int = 0 init( h:Int, w:Int) { self.height = h self.width = w } func getArea() -> Int{ area = height * width return area } } var rect = Rectangle(h: 50, w: 30) var area = rect.getArea() print("W3Adda - Swift Initialiazer With Parameters") print("Area of Rectangle is: \(area)") |
Output:-
Swift Initialization with Multiple Initializers
In swift, we are allowed define multiple initializer init() methods, initializer is executed based on argument list.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Area{ var area:Double init( h:Double, w:Double) { self.area = h * w } init(r: Double) { self.area = 3.14 * r * r } func getArea() -> Double{ return area } } var rect = Area(h: 50, w: 30) var cir = Area(r:3) var a1 = cir.getArea() var a2 = rect.getArea() print("W3Adda - Swift Initialization With Multiple Initializers") print("Area of Circle is: \(a1)") print("Area of Rectangle is: \(a2)") |
Output:-
Swift Initializer with Parameter Names and Argument Labels
In swift, we are allowed define multiple initializer init() methods. In an initializer parameter names are used to refer parameters internally while argument labels are used when initializer is called. As all the initializers are defined with the same name init, then only way to identify which initializer to be executed is argument list. An initializer is invoked based on the number of arguments, name of arguments or type of arguments.
Initializer Parameters Without Argument Labels
If you want to ignore argument labels in initializer parameters, then you can use underscore (_) instead of an external argument label before particular parameter name.
Swift Optional Property Types
In swift, if we have properties with optional type, those properties are automatically initialized with nil or no value during initialization.
Default Initializers
In swift, class or structure is provided with a default initializer which allows it to set default values for all of its properties. The default initializer creates an instance for class or structure itself that sets default values of its properties.
Example:-
1 2 3 4 5 6 7 8 9 10 |
class Employee { var empName: String = "Alex?" var empSalary: Int = 2000 var empAge:Int? } var emp = Employee() print("W3Adda - Swift Default Initializer") print("Employee's Name is :\(emp.empName)") print("Employee's Age is :\(emp.empAge)") print("Employee's Salary is :\(emp.empSalary)") |
Output:-
Swift Initializer Delegation for Value Types
Initializer delegation is a process in which an intializer is allowed to call another initializers to perform part of an instance’s initialization. Initializer delegation helps to avoid duplicate code across multiple initializers. Initializer delegation works in differently for value types and class types.
Initializer Inheritance and Overriding
In swift a subclasses is not allowed to inherit their superclass initializers by default. If a subclass initializer matches a superclass designated initializer, this way you are providing an override for superclass designated initializer. Therefore, you are required to add override modifier before the subclass’s initializer definition, this is applicable even if you are overriding an automatically provided default initializer.Conversely, if a subclass initializer matches a superclass convenience initializer, you are not required to write override modifier when providing a matching
implementation of a superclass convenience initializer.
Swift Failable Initializer
In swift a class, structure or enumeration initializer may fail for any of the following reason –
- Invalid initialization parameter values
- Absence of required external sources
- Conditions that prevents initializer to succeed
In swift a Failable Initializer allow us to catch and notify initializer method exceptions. The failable initializer can be defined by placing question mark after the init keyword (init?). The failable initializer creates an optional value for the type it is initialized, here a return statement with nil value is used to indicate initialization failure.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Employee { let empName: String init?(empName: String) { if empName.isEmpty { return nil } self.empName = empName } } print("W3Adda - Swift Failable Initializer") let emp1 = Employee(empName: "Alex") print(emp1?.empName) let emp2 = Employee(empName: "") print(emp2) |
Output:-
The init! Failable Initializer
The failable initializer created with question mark after init keyword (init?) creates an optional instance of the respective type. In swift there is an alternate way you can create failable initializer by placing an exclamation mark after the init keyword (init!), this way an implicitly unwrapped optional instance is created.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class EmpInfo { var empName: String init!(empName: String) { if empName.isEmpty { return nil } self.empName = empName } } class SalaryInfo: EmpInfo { var empSalary: Int init!(empName: String, empSalary: Int) { if empSalary < 1000 { return nil } self.empSalary = empSalary super.init(empName: empName) } } print("W3Adda - Swift init! Failable Initializer") if var result = SalaryInfo(empName: "John Doe", empSalary: 25000){ print("Name: \(result.empName), Salary: \(result.empSalary)") } if var result1 = SalaryInfo(empName: "John Doe", empSalary: 500){ print("Name: \(result1.empName), Salary: \(result1.empSalary)") } else { print("Unable to Initialize employee Salary") } if var result2 = SalaryInfo(empName: "", empSalary: 25000){ print("Name: \(result2.empName), Salary: \(result2.empSalary)") } else { print("Unable to Initialize employee Name") } |
Here, we have defined a super class “EmpInfo” and sub class “SalaryInfo” with failable initializers to catch exceptions in super and sub classes. As we discussed if one initializer fail, the entire program stops execution immediately.
When we run the above swift program, we see the following output –
Output:-
Required Initializers
In swift, initializer with required modifier is termed as “Required Initializer“, it tells compiler that we must implement the initializer method in all sub classes.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class EmpInfo { required init() { let empName:String = "John" print(empName) } } class SalaryInfo: EmpInfo { required init() { let empSalary:Int = 2000 print(empSalary) } } print("W3Adda - Swift Required Initializer") let empName = EmpInfo() let empSalary = SalaryInfo() |
Output:-