Initializers are special methods that you use to create and customize instances of a structure or class. When you create a new instance, Swift calls the initializer to set up the properties of the new instance.
struct Person {
var name: String
var age: Int
}In the above code, Person is a structure with two properties: name and age. But how do we create a new Person instance? Let's create an initializer for it.
Swift provides two types of initializers:
Designated Initializers: These are the initializers you create to initialize the properties of your structure or class.
Convenience Initializers: These are optional initializers that provide a simpler way to create instances.
To create a designated initializer, you write a method with the same name as the structure or class, and it has self as the first parameter.
struct Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}In the above code, we've created a designated initializer init(name:age:). When you create a new Person instance, Swift automatically calls this initializer.
Convenience initializers are optional initializers that help you create instances in a more convenient way. They call another initializer to set up the properties.
struct Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
convenience init(name: String) {
self.init(name: name, age: 0)
}
}In the above code, we've created a convenience initializer init(name:). This initializer calls the designated initializer init(name:age:) with age set to 0.
Swift can automatically generate initializers for you, known as initializer synthesis. This works for structures and classes that have no computed properties and don't inherit from a superclass.
struct Person {
var name: String
var age: Int
}Swift will automatically generate the following initializers for you:
init() - initializer with no arguments, sets all properties to their default values.init(_:) - initializer that takes each property as a parameter and sets it accordingly.Classes have one more type of initializer: classfunc. This initializer is called when you use the init(className.self) syntax.
class Car {
var brand: String
var model: String
class func defaultCar() -> Car {
return Car(brand: "Toyota", model: "Corolla")
}
init(brand: String, model: String) {
self.brand = brand
self.model = model
}
}
let defaultCar = Car.defaultCar()In the above code, we've created a classfunc initializer defaultCar() that returns a new Car instance with default values.
What does Swift call when you create a new instance of a structure or class?
Which of the following is NOT a type of initializer in Swift?