CODEX
Swift Basics: Introduction to Extensions
Learn what is an extension and how to use extensions to add new functionality to an existing type.
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: