Extensions in Swift

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
May 24, 2023

Using Extensions in Swift

Extensions in Swift are used to extend the functionality of an existing class, struct, enum, or protocol type without modifying its source code. It is a powerful feature of Swift that enables developers to enhance the functionality of existing types with new properties, methods, and initializers.

Creating a Basic Extension

Let's take a look at how to create a basic extension for a Swift class. Suppose you have a class called Person, which represents a person with a name and an age.


class Person {
   var name: String
   var age: Int

   init(name: String, age: Int) {
      self.name = name
      self.age = age
   }
}

You can extend the Person class to add a new computed property that returns the person's initials.


extension Person {
   var initials: String {
      let charaters = name.components(separatedBy: " ")
      return charaters.reduce("") { ($0 == "" ? "" : "\($0.first!)") + "\($1.first!)" }
   }
}

With the extension in place, you can now access a person's initials using the initials property.


let john = Person(name: "John Doe", age: 30)
print(john.initials) // "JD"

Extending Protocols

Extensions can also be used to extend the functionality of existing protocols. Suppose you have a protocol called CanFly, which represents all the objects that can fly.


protocol CanFly {
   func fly()
}

You can use an extension to add a default implementation for the fly() method.


extension CanFly {
   func fly() {
      print("The object is flying.")
   }
}

Now, any struct or class that conforms to the CanFly protocol can gain this default behavior. If you create a class or struct that implements the CanFly protocol but doesn't implement the fly() method, the default implementation in the extension will be used.

Extending Generic Types

Extensions can also be used to extend the functionality of generic types. Suppose you have a generic type called Box, which represents any object you want to encapsulate in this box.


struct Box<T> {
   var element: T
}

You can extend the Box type to add a new method that prints the contents of the box.


extension Box {
   func printElement() {
      print("The contents of the box are: \(element)")
   }
}

Now, you can create an instance of the Box type and then call the printElement() method to print its contents.


let box = Box(element: "Hello, World!")
box.printElement() // "The contents of the box are: Hello, World!"

Summary

Extensions in Swift are a powerful feature that allow developers to add new method, properties, and initializers to an existing type, as well as to extend the functionality of existing protocols and generic types. They are easy to use and can help make your code more modular and extensible.