What if you could teach numbers and strings new tricks, just like your own custom tools?
Why Extending built-in types in Swift? - Purpose & Use Cases
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.
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.
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.
func isEven(_ number: Int) -> Bool {
return number % 2 == 0
}
let result = isEven(4)extension Int {
var isEven: Bool {
return self % 2 == 0
}
}
let result = 4.isEvenYou can make your code more natural and expressive by adding your own features to existing types.
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.
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.