0
0
Swiftprogramming~3 mins

Why Adding initializers via extension in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add new ways to create objects without ever touching the original code?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
struct Person {
    var name: String
    var age: Int
    
    init(name: String) {
        self.name = name
        self.age = 0
    }
}
After
struct Person {
    var name: String
    var age: Int
}

extension Person {
    init(name: String) {
        self.init(name: name, age: 0)
    }
}
What It Enables

You can easily add new initializers anytime, even for types you don't own, making your code more powerful and adaptable.

Real Life Example

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.

Key Takeaways

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.