0
0
Swiftprogramming~3 mins

Why Extending built-in types in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could teach numbers and strings new tricks, just like your own custom tools?

The Scenario

Imagine you want to add a new feature to a number or a string in your program, like making a number tell if it's even or odd, but the built-in number type doesn't have that feature.

You try to write separate functions everywhere to check this, but it feels messy and repetitive.

The Problem

Writing separate functions for every new feature is slow and confusing.

You have to remember to call the right function each time, and it's easy to make mistakes or forget.

Your code becomes long and hard to read because the new features don't feel like they belong to the numbers or strings themselves.

The Solution

Extending built-in types lets you add new features directly to existing types like numbers or strings.

This means you can call your new features just like the built-in ones, making your code cleaner and easier to understand.

Before vs After
Before
func isEven(_ number: Int) -> Bool {
    return number % 2 == 0
}

let result = isEven(4)
After
extension Int {
    var isEven: Bool {
        return self % 2 == 0
    }
}

let result = 4.isEven
What It Enables

You can make your code more natural and expressive by adding your own features to existing types.

Real Life Example

Imagine adding a feature to the String type that tells if a password is strong, so you can just write password.isStrong instead of calling a separate function.

Key Takeaways

Manual functions for new features are repetitive and messy.

Extending built-in types adds features directly to existing types.

This makes code cleaner, easier to read, and more natural.