Designated and Convenience Initializers in Swift

All of a class’s stored properties—including any properties the class inherits from its superclass—must be assigned an initial value during initialization.

Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. These are known as designated initializers and convenience initializers.

Normally you would have a single init method. You would initialize it using the above call.

class Test {
	init() {
		print("init method 1")
	}
}
var testObj1 = test()

Consider you need to initialize it with a name. Then you would add another initializer as shown below.

At this point you would need to add a convenience keyword for the init function.

class Test {
	init() {
		print("init method 1")
	}
	convenience init(name: String) {
		self.init()
		print("init method with 1 parameter", name)
	}
	convenience init(name: String, number : Int) {
		self.init(name: name)
		print("init method 2 parameters", name, number)
	}
}
var testObj1 = test(name: "shi", number: 1)

It’s that simple. Convenience initializers are basically used to call the init method of the same class.

Now lets move on to the designated initializers. This doesn’t have a keyword per se.

The normal init method is also a designated initializer. This comes into play during inheritance.

Designated initializers are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.

At the end of the day, if you have more than one init method in a class during inheritance, you would need to designate a init method of the superclass.

class A {
	
	init() {
		print("inside class a")
	}
	
	init(name: String, distance: Int) {
		print(" "+name)
	}
}

class B : A {
	override init() {
		super.init()
		print("inside class b ")
	}
	
	func methodb() -> Void {
		print("methodb in B")
	}
	
	override init(name: String, distance: Int) {
		super.init()
		print(" "+name)
	}
}

class C : B {
	
	override init() {
		super.init()
		print("inside class c")
	}
		
	override func methodb() -> Void {
		print("methodb in C")
	}
}

var obj = C()

Leave a Reply

Your email address will not be published. Required fields are marked *