Convenience initializers help you create objects easily by providing shortcuts to set up common values.
0
0
Convenience initializers in Swift
Introduction
When you want to create an object with default or common settings quickly.
When you want to offer multiple ways to create an object without repeating code.
When you want to simplify object creation for users of your class.
When you want to call a main initializer but with fewer parameters.
When you want to avoid writing the same setup code in many places.
Syntax
Swift
convenience init(parameters) { self.init(otherParameters) // additional setup }
A convenience initializer must call another initializer from the same class.
It cannot fully initialize the object alone; it relies on a designated initializer.
Examples
This class has a main initializer and a convenience initializer that sets a default color.
Swift
class Car { var color: String var model: String init(color: String, model: String) { self.color = color self.model = model } convenience init(model: String) { self.init(color: "Black", model: model) } }
The convenience initializer creates a square by using the main initializer with equal width and height.
Swift
class Rectangle { var width: Double var height: Double init(width: Double, height: Double) { self.width = width self.height = height } convenience init(size: Double) { self.init(width: size, height: size) } }
Sample Program
This program shows a class with a main initializer and a convenience initializer that sets a default author.
Swift
class Book { var title: String var author: String init(title: String, author: String) { self.title = title self.author = author } convenience init(title: String) { self.init(title: title, author: "Unknown") } } let book1 = Book(title: "Swift Basics", author: "Alice") let book2 = Book(title: "Learning Swift") print("Book1: \(book1.title) by \(book1.author)") print("Book2: \(book2.title) by \(book2.author)")
OutputSuccess
Important Notes
Convenience initializers make your code cleaner and easier to use.
They always call a designated initializer to ensure the object is fully set up.
Convenience initializers can call other convenience initializers from the same class, but the chain must end with a designated initializer.
Summary
Convenience initializers provide easy shortcuts to create objects.
They must call a designated initializer in the same class.
Use them to avoid repeating code and to offer default values.