What if you could create objects in many ways without rewriting the same code over and over?
Why Convenience initializers in Swift? - Purpose & Use Cases
Imagine you have a class with many properties, and you want to create objects with different sets of starting values. Writing separate full initializers for each case means repeating a lot of code.
Manually writing many initializers is slow and error-prone. You might forget to set some properties or repeat the same code again and again, making your code messy and hard to maintain.
Convenience initializers let you write small, simple starting points that call a main initializer. This keeps your code clean, avoids repetition, and makes creating objects easier and safer.
class Car { var color: String var model: String init(color: String, model: String) { self.color = color self.model = model } init() { self.color = "Red" self.model = "Sedan" } }
class Car { var color: String var model: String init(color: String, model: String) { self.color = color self.model = model } convenience init() { self.init(color: "Red", model: "Sedan") } }
It enables you to create flexible and readable object setups without repeating code, making your programs easier to write and maintain.
Think of a game where you create characters. You can have a main initializer for all details, and convenience initializers for quick setups like a default warrior or mage, saving time and avoiding mistakes.
Convenience initializers reduce code repetition by calling a main initializer.
They make creating objects with default or partial data easier and safer.
Using them keeps your code clean and easier to maintain.