In Swift, you can use extensions to add new functionality to an existing type (class, structure, enumeration, or protocol).
Using extensions allows you to organize code.
Extensions are also useful when you don’t have access to the original source code, for example when working with some built-in types in Swift.
In Swift, you can create an extension by using the extension
keyword:
extension SomeExistingType {
// add new functionality to SomeExistingType here
}
How to Organize Code with Extensions
Let’s say you have a Fruit
structure:
struct Fruit {
let name: String
init(name: String) {
self.name = name
}
}
But you’d like to be able to use an instance of Fruit
to print info about it, for example by fruit.info()
.
Of course, you could modify the existing functionality by implementing the info
method there. But there is another way to do it by using an extension:
You can create a completely new dedicated file in your project and add the following extension to it:
extension Fruit {
func info(){
print("I am a \(self.name)")
}
}
Even though this extension is in a different file, it successfully extends the base implementation of the Fruit structure. Now you can work with instances of Fruit
as follows:
let banana = Fruit(name: "Banana")
banana.info() // prints "I am a Banana"
Working with extensions this way can help you organize code. As you saw, you can group parts of the code in the Fruit
structure into separate files if you want.
Extend the Built-in Types in Swift
Another common use case for an extension is when you can’t modify the original source code.
For example, if you need to modify a built-in type in Swift, you can use extensions to accomplish this.
Let’s demonstrate this by calculating pounds from a double (assuming a double represents weight in kilograms). To do this, you need to extend the built-in implementation of Double
type of Swift:
extension Double {
var pounds: Double { return self * 2.205 }
}
Now you can simply access the pounds
property of a double:
let kilos: Double = 100.0
print(kilos.pounds) // prints "220.5"
(This particular example is impractical as you could call kilos.pounds.pounds.pounds
… But you get the gist of how to extend built-in types in Swift this way.)
Conclusion
In Swift, Extensions can be used to add new functionality to an existing type.
Extensions are useful when you want
- To organize your code.
- More functionality to an existing type that you can’t directly modify