Swift Initialization

In swift, initialization is a special type of method in class, structure or enumeration and it is responsible for making sure a newly created instance of class, structure or enumeration is fully initialized and perform other tasks that are required before the new instance is ready for use in our applications.

 

In swift we can implement the initialization process by defining special methods called initializers, these methods will call during the creation of a new instance of particular type and these initializers are responsible for making sure that new instances of particular type correctly initialized before they are used for the first time.

 

Generally in classes, structures, and enumerations we must need to set the initial values for all the properties which are defined by the time of an instance created for the class or structure.

 

In swift, we can set the initial values for class, structure stored properties within the initializer or we can set the default values for defined properties in class or structure as a part of the definition.

 

In swift initializers are represented by init keyword and these initializers are called during the creation of a new instance for a particular class or structure.

Swift Initializer Syntax

Following is the syntax of defining initializer in swift programming language.

 

init() {

//  initialization here

}

If you observe the above syntax we defined an initializer using init keyword and the initialization of class or structure properties can be done within the initializer init() method.

 

Now we will see how to initialize properties of class or structure during its definition and in initializer with examples.

Swift Initialization Example

Following is the example of declaring and defining properties of class inside of the initializer and outside of the initializer during its definition.

 

class concatenate {

var fname: String = "Suresh"

var lname: String = " Dasari"

var fullname : String

init() {

fullname = fname + lname

}

}

var name = concatenate()

print("Full Name: \(name.fullname)")

If you observe above example we defined a three (fname, lname and fullname) properties and defined a initializer init() method. For fname and lname properties we assigned values during its declaration and for fullname property initial value will be assigned in initializer init() method during creation of an instance for class concatenate.

 

When we run above example in swift playground we will get result like as shown below

 

Full Name: Suresh Dasari

This is how we can use the initializer in a swift programming language based on our requirements.

Swift Initialization with Parameters

In swift initializer init() method we can send initialization parameters as a part of its definition same as functions and methods parameters.

 

Following is the example of sending initialization parameters as a part of an initializers init() method.

 

class concatenate {

var fullname : String

init(firstname fname: String, lastname lname: String ) {

fullname = fname + lname

}

}

var name = concatenate(firstname: "Suresh", lastname: " Dasari")

print("Full Name:  \(name.fullname)")

If you observe above example we are sending an initialization parameters with argument labels (firstname, lastname) and parameter names (fname, lname) as a part of init() method definition.

 

When we run above example in swift playground we will get result like as shown below

 

Full Name: Suresh Dasari

This is how we can send parameters to the initializer in a swift programming language based on our requirements.

Swift Initialization with Multiple Initializers

We can use multiple initializer init() methods to initialize properties based on our requirements. 

 

Following is the example of defining multiple initializer init() methods to initialize properties in a class.

 

class concatenate {

var fullname : String

init(fname: String, lname: String ) {

fullname = fname + lname

}

init(firstname: String, lastname: String ) {

fullname = firstname + lastname

}

}

var name = concatenate(fname: "Suresh", lname: " Dasari")

print("Full Name:  \(name.fullname)")

var cname = concatenate(firstname: "Rohini", lastname: " Alavala")

print("Full Name:  \(cname.fullname)")

If you observe above example we defined multiple initializer init() methods  to initialize properties of class during creation of an instance.

 

When we run above example in swift playground we will get result like as shown below

 

Full Name: Suresh Dasari

Full Name: Rohini Alavala

This how we can define multiple initializers in a swift programming language based on our requirements.

Swift Initializer with Parameter Names and Argument Labels

In swift, initialization parameters can have parameter names and argument labels. In initialization parameter names are used within the initializer body and argument labels are used when calling the initializer.

 

In swift, initializers don’t have any identifying names like functions or methods so the initialization parameters will play an important role to identify which initializer should be called and swift provides automatic argument labels for every parameter in an initializer init() method in case if we didn’t provide one.

 

Following is the example of defining the initializer init() method with or without argument labels and parameter names.

 

class concatenate {

let fname, lname : String

 

init(fname: String, lname: String ) {

self.fname = fname

self.lname = lname

}

init(firstname: String, lastname: String ) {

fname = firstname

lname = lastname

}

}

var name = concatenate(fname: "Suresh", lname: "Dasari")

print("Full Name:  \(name.fname) \(name.lname)")

var uname = concatenate(firstname: "Rohini", lastname: "Alavala")

print("Full Name:  \(uname.fname) \(uname.lname)")

If you observe above example we created an initializers only with parameter names so we used parameter names to call the initializers.

 

When we run above example in swift playground we will get result like as shown below

 

Full Name: Suresh Dasari

Full Name: Rohini Alavala

Note: In case if we define argument labels in initializers it’s mandatory to call the initializer with argument labels otherwise we will get a compile-time error.

Swift Initializer Parameters without Argument Labels

In case if we don’t want to use argument labels in initializer parameters, use underscore (_) instead of an explicit argument label for a particular parameter in the initializer to override the default behavior.

 

Following is the example of defining initializer parameters without argument labels in swift programming language.

 

class concatenate {

var fullname : String

init(firstname fname: String, lastname lname: String ) {

fullname = fname + lname

}

init(_ fname: String, _ lname: String ) {

fullname = fname + lname

}

}

var name = concatenate(firstname: "Suresh ", lastname: "Dasari")

print(name.fullname)

 

var uname = concatenate("Rohini ","Alavala")

print(uname.fullname)

If you observe the above example we defined two initializers one with argument labels and another one with an underscore (_) in the initializer to override the external argument labels.

 

When we run above example in swift playground we will get result like as shown below

 

Suresh Dasari

Rohini Alavala

This is how we can use initializer parameters in a swift programming language to initialize the values before the instance of class or structure.

Swift Optional Property Types

In initialization, we can also declare an optional value for stored properties which accepts nil or no value. The properties with optional types are automatically initialized with nil or no value during initialization.

 

Following is the example of defining a class concatenate, with an optional property fullname in swift programming language.

 

class concatenate {

var fname,lname : String

var fullname : String?

init(firstname: String, lastname: String ) {

self.fname = firstname

self.lname = lastname

}

func userdetails()  {

print(fname + lname)

}

}

var name = concatenate(firstname: "Suresh ",lastname: "Dasari")

name.userdetails()

print(name.fullname)

name.fullname = "Welcome to Tutlane"

print(name.fullname)

If you observe above example we defined an optional property “fullname” with a type “String?” and the value of “fullname” will be nil or no value until we call that property and assign some value.

 

When we run above example in swift playground we will get result like as shown below

 

Suresh Dasari

nil

Optional("Welcome to Tutlane")

This is how we can define optional properties in a swift programming language based on our requirements.

Swift Modify Constant Properties during Initialization

In swift, we can assign a value to a constant property at any point during initialization. Once we assign a value to the constant property, further it cannot be modified.

 

Following is the example of defining a class UserDetails, with constant property name in a swift programming language.

 

class UserDetails {

let name : String

init(name: String) {

self.name = name

}

func username()  {

print(name)

}       

}

var uname = UserDetails(name: "Suresh Dasari")

uname.username()

If you observe above example we defined constant property “name” with a type “let” and the value of “name” will be set during initialization of class instance. Once we assigned a value to constant property it won’t allow us to modify the value.

 

When we run above example in swift playground we will get result like as shown below

 

Suresh Dasari

This is how we can define constant properties in a swift programming language based on our requirements.

Swift Default initializers

Swift provides a default initializer for class or structure to set default values for all the properties in class or structure. The default initializer will create a new instance for class or structure with all of its properties to set their default values.

 

Following is the example of defining a class Student, with three properties name, position, and location in swift programming language.

 

class Student {

var name: String?

var position = "Team Lead"

var location = "Hyderabad"

}

var stu = Student()

print(stu.name)

print(stu.position)

print(stu.location)

In the above example, we created a class Student with three properties and assigned default values. The Student class will behave as a default initializer and that will create a new instance with all of its properties to set their default values.

 

When we run above example in swift playground we will get result like as shown below

 

nil

Team Lead

Hyderabad

This is how we can use default initializers in a swift programming language based on our requirements.

Swift Initializer Delegation for Value Types

Initializer delegation is the process in which Initializer can call another Initializer as part of instance’s Initialization. 

 

By following the initializer delegation process, we can avoid the code duplication across the multiple Initializers and by using self.init we can achieve the initializer delegation process. We can use self.init only within our custom initializers.

 

Following is the example of using the initializer delegation process in swift programming language.

 

struct numbers1 {

var a = 0, b = 0

}

struct numbers2{

var x = 0, y = 0

}

struct calculate{

var addition = numbers1()

var multiplication = numbers2()

init(){

}

init(addition : numbers1, multiplication : numbers2){

self.addition = addition

self.multiplication = multiplication

}

init(add : numbers1, mul : numbers2){

let ad = 100 + add.a

let ad1 = 500 + add.b

let mu = 10 * mul.x

let mu1 = 20 * mul.y

self.init(addition: numbers1(a: ad, b: ad1), multiplication: numbers2(x: mu, y: mu1))

}

}

let  result = calculate()

print("Initial Values:  \(result.addition.a, result.addition.b), \(result.multiplication.x, result.multiplication.y)")

 

let  result1 = calculate(addition: numbers1(a:100,b:100), multiplication: numbers2(x:10,y:20))

print("Result1 Values:  \(result1.addition.a, result1.addition.b), \(result1.multiplication.x, result1.multiplication.y)")

 

let  result2 = calculate(add: numbers1(a:100,b:100), mul: numbers2(x:10,y:20))

print("Result2 Values:  \(result2.addition.a, result2.addition.b), \(result2.multiplication.x, result2.multiplication.y)")

If you observe above example we created a multiple initializers and calling one initializer from another initializer using self.init initializer deleation.

 

When we run above example in swift playground we will get result like as shown below

 

Initial Values: (0, 0), (0, 0)

Result1 Values: (100, 100), (10, 20)

Result2 Values: (200, 600), (100, 400)

This is how we can use initializer delegation to call one initializer from another initializer in a swift programming language based on our requirements.

 

The initializer delegation process is different for value types and reference types because value types don’t support inheritance so the initializer delegation process is simple by using self.init but reference types like classes can inherit from other classes so it needs to check whether all the stored properties are inheriting suitable value or not during initialization.

Swift Failable Initializer

In swift, we can notify the user in case of any initializer failures while defining a class, structure or enumeration. The initializer failure can be happened due to following reasons.

 

  • Invalid initialization parameter values
  • Absence of required external sources
  • Some conditions that prevents initializer to succeed

In swift, we can catch initializer method exceptions by using an initializer called “Failable Initializer”. By using a failable initializer as a part of classstructure,  or enumeration definition we can let the user know that something is missing during initialization. 

 

In swift, we can define a failable initializer by placing a question mark after the init keyword (init?). By defining failable initializer it will create an optional value of the type it initializes and we can write return nil within failable initializer to indicate a point where the initialization can be failed.

 

Now we will see how to use failable initializer in swift programming language with examples.

 

Following is the example of using a failable initializer to catch the exceptions thrown by the initializer in swift programming language.

 

class Name {

let fullname: String

init?(FullName: String) {

if FullName.isEmpty { return nil }

self.fullname = FullName

}

}

let ins1 = Name(FullName: "Suresh Dasari")

print(ins1?.fullname)

let ins2 = Name(FullName: "")

print(ins2)

If you observe above example we defined a class “Name” with failable initializer (init?) and returning nil wherever the initialization failure can trigger.

 

When we run above example in swift playground we will get result like as shown below

 

Optional("Suresh Dasari")

nil

This is how we can use failable initializers as a part of class, structure or enumeration definition to catch initializer exceptions.

Swift Failable Initializers for Enumerations

In swift, we can use failable initializers in enumerations to select appropriate enumeration case based on input parameters. 

 

In enumeration initialization in case the provided input parameter not matched with any of the defined enumeration cases then it will throw an error so by using failable initializer we can handle those exceptions in enumerations.

 

Following is the example of using failable initializers in enumerations to handle errors in enumeration initialization in a swift programming language.

 

enum Student {

case Suresh, Rohini, Trishika

init?(symbol: Character) {

switch symbol {

case"S":

self = .Suresh

case"T":

self = .Trishika

case"R":

self = .Rohini

default:

return nil

}

}

}

 

let ins1 = Student(symbol: "T")

if ins1 != nil {

print("Enumeration Initialization Success")

}

let ins2 = Student(symbol: "Z")

if ins2 == nil {

print("No Enumeration Case Matched. Initialization Failed")

}

If you observe above example we defined an enumeration “Student” with multiple enumeration cases and used a failable initializer (init?) to handle exceptions in enumerations.

 

When we run above example in swift playground we will get result like as shown below

 

Enumeration Initialization Success

No Enumeration Case Matched. Initialization Failed

This is how we can use failable initializers in enumerations to handle exceptions based on our requirements in swift programming language.

Swift Failable Initializer in Super and Sub Class

In swift failable initializer of one class, structure or enumeration can delegate to another failable initializer from the same or another class, structure or enumeration. 

 

The superclass Failable initializer delegate will point to the subclass Failable initializer so if one failable initializer is fail, the entire initialization of the whole program will fail immediately.

 

Following is the example of defining failable initializers in superclass and subclass in swift programming language.

 

class UserDetails {

var name: String

init?(name: String) {

if name.isEmpty { return nil }

self.name = name

}

}

class SalaryInfo: UserDetails {

var salary: Int

init?(name: String, salary: Int) {

if salary 1000 { return nil }

self.salary = salary

super.init(name: name)

}

}

if var result = SalaryInfo(name: "Trishika Dasari", salary: 50000){

print("Name:  \(result.name), Salary:  \(result.salary)")

}

if var result1 = SalaryInfo(name: "Trishika Dasari", salary: 500){

print("Name:  \(result1.name), Salary:  \(result1.salary)")

}

else {

print("Unable to Initialize Salary")

}

if var result2 = SalaryInfo(name: "", salary: 50000){

print("Name:  \(result2.name), Salary:  \(result2.salary)")

}

else {

print("Unable to Initialize Name")

}

If you observe above example we defined a super class “UserDetails” 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 above program in swift playground we will get result like as shown below

 

Name: Trishika Dasari, Salary: 50000

Unable to Initialize Salary

Unable to Initialize Name

This is how we can use failable initializers in super class and subclass to catch exceptions in a swift programming language.

Swift Override a Failable Initializer

Generally in swift overriding is the process in which we can override a super class method or function by implementing the same method in sub class with custom functionality. 

 

In swift we can override a super class failable initializer in subclass based on our requirements. Failable initializer in super class can also be overridden with non-failable initializer in sub class.

 

If we override a super class failable initializer with a subclass non-failable initializer, the only way to delegate up to super class initializer is to force-unwrap the result of the super class failable initializer. 

 

Following is the example of overriding a super class failable initializer in sub class in a swift programming language.

 

class Person {

var name: String?

init() {}

init?(name: String) {

if name.isEmpty { return nil }

self.name = name

}

}

class Student: Person {

override init() {

super.init()

self.name = "Suresh Dasari"

}

override init?(name: String) {

super.init()

if name.isEmpty { return nil }

else{

self.name = name

}

}

}

var stu1 = Student(name: "Trishika Dasari")

print(stu1?.name)

var stu2 = Student(name: "")

print(stu2?.name)

If you observe above example we created a super class “Person” and sub class “Student” and overriding super class failable initializer in subclass using override keyword.

 

When we run above example in swift playground we will get result like as shown below

 

Optional("Trishika Dasari")

Nil

This is how we can override super class failable initializers in sub class to implement our own custom functionality based on our requirements in swift programming language.

Swift init! Failable Initializer

Generally, in swift we will define a failable initializer by placing a question mark (?) sign after init keyword and that will create an optional instance of the appropriate type. Alternatively, we can create a failable initializer by placing an exclamation mark (!) sign after init keyword (init!).

 

Following is the example of defining a failable initializers with an exclamation mark (!) in super class and subclass in a swift programming language.

 

class UserDetails {

var name: String

init!(name: String) {

if name.isEmpty { return nil }

self.name = name

}

}

class SalaryInfo: UserDetails {

var salary: Int

init!(name: String, salary: Int) {

if salary 1000 { return nil }

self.salary = salary

super.init(name: name)

}

}

if var result = SalaryInfo(name: "Trishika Dasari", salary: 50000){

print("Name:  \(result.name), Salary:  \(result.salary)")

}

if var result1 = SalaryInfo(name: "Trishika Dasari", salary: 500){

print("Name:  \(result1.name), Salary:  \(result1.salary)")

}

else {

print("Unable to Initialize Salary")

}

if var result2 = SalaryInfo(name: "", salary: 50000){

print("Name:  \(result2.name), Salary:  \(result2.salary)")

}

else {

print("Unable to Initialize Name")

}

If you observe above example we defined a super class “UserDetails” 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 above program in swift playground we will get result like as shown below

 

Name: Trishika Dasari, Salary: 50000

Unable to Initialize Salary

Unable to Initialize Name

This is how we can use the exclamation mark (!) with init keyword to define failable initializers in super class and subclass to catch exceptions in swift programming language.

Swift Required Initializers

In swift, the Required initializer tells the compiler that we must need to implement the initializer method in all sub classes. By using the “required” keyword along with init keyword we can define a required initializer that needs to implement in all sub classes.

 

Following is the example of defining required initializers in super and sub classes in swift programming language.

 

class UserDetails {

required init() {

var x = 100

print(x)

}

}

class SalaryInfo: UserDetails {

required init() {

var y = 500

print(y)

}

}

let result = UserDetails()

let result1 = SalaryInfo()

If you observe above example we defined a super class “UserDetails” and sub class “SalaryInfo” with required failable initializers.

 

When we run the above program in swift playground we will get the result like as shown below

 

100

500

100

This is how we can use required failable initializers in super class to make sure sub classes implement super class defined initializer.