9.1.2. Initializing structs with different initializers
We can define multiple initializers in a struct. At this point, we will define a new struct Car to demonstrate this concept. Let's define Car:
struct Car{
var make:String
var model:String
var year:Int
init(){
make = "Not set"
model = "Not set"
year = 0
}
}
//creating an instance of Car...
var car = Car()
//printing the instance...
print(car)
It prints:
Here, we can see that all the default values were set when we created the instance.
Now, let's define another custom init() method along with the default one. This custom init() will accept parameters when we are creating the instance.
Do you see the self keyword? What do you think it is? - self is used to refer to the current instance of Car. See, we are using the same names for the parameters the method accepts as the properties of Car. By writing self.make = make, we are instructing the program to set the value of the current instance's make property to the value of the parameter make accepted by the init() method.
Now, we can create an instance of Car by calling the new init(make:String, model:String, year:Int) method. Let's try:
It prints:
So yes! We can create instances of a struct using multiple init() methods.
Struct initialization and Optionals
Let's continue with the same Car example. Let's assume that when we are creating an instance of Car struct, we only want to set the values for two parameters, make and model, and keep the value of year empty. We can write a new init() method like:
If we add this method, we will see an error:

So it is saying that we need to initialize all stored properties (year is not initialized). Now, how can we initialize make and model without initializing year?
Remember Optional?
Yes, we can declare year as an Optional like the following:
Now that we do not have the error anymore, we can create an instance of Car and initialize it:
Do you see an issue? year is wrapped with Optional. So if you want to use it anywhere, we should use an unwrapping technique like if-let.
Source code
Last updated
Was this helpful?