Swift error: return from initializer without initializing all stored properties

The swift error: return from initializer without initializing all stored properties, occurs when all the properties in the structure  are not initialized in the init method.

Let us recreate this scenario. We shall define a structure with three properties but only two of them are initialized in init method.

main.swift

</>
Copy
struct car {
   var brand: String
   var name: String
   var capacity: Int
   
   init(brand: String, name: String) {
      self.brand = brand
      self.name = name
   }
}

let car1 = car(brand: "Hyundai", name: "Creta")

print("Car details\n-----------")
print("Brand is \(car1.brand)")
print("Name is \(car1.name)")
print("Seating capacity is \(car1.capacity)")

Output

main.swift:9:4: error: return from initializer without initializing all stored properties
   }
   ^
main.swift:4:8: note: 'self.capacity' not initialized
   var capacity: Int
       ^

How to resolve this issue?

To solve this issue, we have to initialize all the properties of the structure in the init method or provide a default value to the property while declaring the property in the structure.

Solution 1: Initialize all properties in init method

Let us initialize all the methods in the init method of structure. Also, we will provide all the arguments during structure call.

main.swift

</>
Copy
struct car {
   var brand: String
   var name: String
   var capacity: Int
   
   init(brand: String, name: String, capacity: Int) {
      self.brand = brand
      self.name = name
      self.capacity = capacity
   }
}

let car1 = car(brand: "Hyundai", name: "Creta", capacity: 5)

print("Car details\n-----------")
print("Brand is \(car1.brand)")
print("Name is \(car1.name)")
print("Seating capacity is \(car1.capacity)")

Output

Car details
-----------
Brand is Hyundai
Name is Creta
Seating capacity is 5

Solution 2: Provide a default value to the property

We can also provide a default value to the properties that are not initialized in the init method.

main.swift

</>
Copy
struct car {
   var brand: String
   var name: String
   var capacity = 5
   
   init(brand: String, name: String) {
      self.brand = brand
      self.name = name
   }
}

let car1 = car(brand: "Hyundai", name: "Creta")

print("Car details\n-----------")
print("Brand is \(car1.brand)")
print("Name is \(car1.name)")
print("Seating capacity is \(car1.capacity)")

Output

Car details
-----------
Brand is Hyundai
Name is Creta
Seating capacity is 5