CODEX

Swift Basics: Introduction to Extensions

Learn what is an extension and how to use extensions to add new functionality to an existing type.

Artturi Jalli
CodeX
Published in
3 min readMar 27, 2021

--

Photo by AltumCode on Unsplash

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…

--

--

Artturi Jalli
CodeX
Writer for

Youtube: @jalliartturi to take your blog to the next level