Extensions in Swift
Extensions
in Swift allow us to add new functionality to existing Classes
, Structures
, Enumerations
, or Protocol
types. This includes adding new methods, properties, initializers, and more. Extensions are particularly useful for organizing and modularizing our code without needing to modify the original type, especially when we don't have access to the original source code.
Extension syntax
To create an extension, we use the extension
keyword followed by the name of the type we want to extend.
Let's explore some practical examples to understand how extensions work in Swift.
Adding custom functionality to existing types
Adding computed properties
Extensions allow us to add computed properties. For example, we can add a computed property that determines if an integer is even or odd.
Adding Methods
Suppose we have a String
type and want to add a method that reverses the string. Instead of modifying the String
type itself, we can create an extension that adds a new method.
If a method needs to modify (or mutate) the instance itself, we need to mark the method as mutating
. The example below adds a new mutating method called square to Swift’s Int type, which squares the original value.
Adding Initializers
Extensions can also provide additional initializers. For example, we can add an initializer that creates a Date
instance from a timestamp.
Adding Subscripts
Extensions can add new subscripts to an existing type. For example, we can add a subscript that returns the character at a given index in the string.
Adding functionality to custom types
Adding computed properties
We can also add computed properties to a type using extensions. For instance, for the Person
class, we might add a computed property that determines if the person is an adult.
Adding methods
Suppose we have a Circle
class and want to add a method that calculates the area of the circle. We can do this using extensions.
Constraints for extensions
Constraints on extensions in Swift allow us to extend a type only when it meets certain conditions. This is especially useful when we want to add functionality to a type that conforms to a specific protocol or has certain properties.
In the example below, we will create an extension on Array that only works when the elements of the array conform to the Numeric protocol. We will add a method called sum() that calculates the sum of the elements in the array.
Protocol extensions
In Swift, we can also extend protocols. It works pretty much like abstract classes when regarding a functionality we want to be available in all the classes that implements some protocol (without having to inherit from a base common class).
Last updated