What if you could add new ways to create objects without ever touching the original code?
Why Adding initializers via extension in Swift? - Purpose & Use Cases
Imagine you have a Swift struct or class, and you want to create new ways to make instances of it. Without extensions, you have to change the original code every time you want a new initializer.
This manual way is slow and risky. Changing original code can cause bugs, and if the code is from a library, you can't change it at all. You end up repeating code or making messy workarounds.
Adding initializers via extension lets you add new ways to create instances without touching the original code. It keeps your code clean, safe, and flexible.
struct Person {
var name: String
var age: Int
init(name: String) {
self.name = name
self.age = 0
}
}struct Person {
var name: String
var age: Int
}
extension Person {
init(name: String) {
self.init(name: name, age: 0)
}
}You can easily add new initializers anytime, even for types you don't own, making your code more powerful and adaptable.
Suppose you use a library with a Date type. You want to create a Date from a string. You can add an initializer in an extension to do this without changing the library code.
Adding initializers via extension avoids changing original code.
It keeps your code clean and safe from bugs.
It allows flexible ways to create instances anytime.