I am having troubles to understand the difference between both, or the purpose of the convenience init
.
Here is a simply example, taken from the Apple Developer portal.
Basicly the designated initializer is the init(name: String)
, it ensure that all stored properties are initialized.
The init()
convenience initializer, taking no argument, automaticly sets the value of name
stored property to [Unnamed]
by using the designated initializer.
class Food {
let name: String
// MARK: - designated initializer
init(name: String) {
self.name = name
}
// MARK: - convenience initializer
convenience init() {
self.init(name: "[Unnamed]")
}
}
// MARK: - Examples
let food = Food(name: "Cheese") // name will be "Cheese"
let food = Food() // name will be "[Unnamed]"
It is usefull, when you are dealing with large classes, with at least a few stored properties. I would recommend to read some more about optionals and inheritance at the Apple Developer portal.