Junior — Middle
What types of constructors are implemented in a class and how do they differ?
sobes.tech AI
Answer from AI
In Swift, classes typically implement the following types of initializers:
-
Default initializer — automatically created if all properties have default values and no other initializers are defined.
-
Designated initializer — the primary initializer that initializes all properties of the class. Other initializers within the class call
self.init. -
Convenience initializers — auxiliary initializers that call designated initializers. They simplify creating objects with different parameter sets.
Differences:
- Designated initializers initialize all properties and call superclass initializers.
- Convenience initializers call other initializers of the same class and cannot directly initialize properties.
Example:
class Person {
var name: String
var age: Int
// Designated initializer
init(name: String, age: Int) {
self.name = name
self.age = age
}
// Convenience initializer
convenience init(name: String) {
self.init(name: name, age: 0) // call designated
}
}
Thus, constructors provide flexibility in object initialization with different parameters and ensure all properties are properly initialized.