designated init in extension

In Swift, why cannot we add designated initializers in extension?

If you try to add designated init to an extension, you will receive the following error form the Swift compiler:

Designated initializer cannot be declared in an extension of ‘SomeClass’; did you mean this to be a convenience initializer?

Swift error

To know what are the differences between designated and convenience initializers refer to the Swift documentation.

In Swift, if a subclass does not provide any initializer, the subclass inherits the initializers of the superclass. Suppose the Shape and Rectangle classes. Rectangle inherits from Shape.

class Shape {
	var backgroundColor: UIColor?
	
	init(backgroundColor: UIColor?) {
		self.backgroundColor = backgroundColor
	}
}

class Rectangle: Shape {
	
	var width: Int = 0
	var height: Int = 0
}

As Rectangle does not have any initializers, it inherits the init(backgroundColor:) from the Shape and can be instantiated as below:

let rectangle = Rectangle(backgroundColor: UIColor.green)

Now imagine we could add designated initializers by extensions like this:

extension Rectangle {
	init(backgroundColor: UIColor?, width: Int, height: Int) {
		self.width = width
		self.height = height
		super.init(backgroundColor: backgroundColor)
	}
}

From now on, the Rectangle class Will have a designated initializer for its own, hence, the Swift will remove the inherited initializer init(backgroundColor:) from the Rectangle. So what will happened to the codes that used the inherited initializer to instantiate the Rectangle. All of them would be invalid. Now suppose the Shape and Rectangles are classes that have been defined in one of the Apple frameworks. Good job. We managed to make Apple frameworks invalid. Therefore, it is reasonable that Swift does not allow us add designated initializers using the extensions.


Posted

in

by