Swift Extensions

Here we will explain Extensions in Swift.

Using Extensions in Swift

By using Extensions in Swift, you can add functionality to existing classes, structs, enums, and more.

They are useful when you want to add functionality without modifying the original code, or when you want to separate functionality for better source code organization.


You can add an Extension using the following syntax:

extension TypeName {
    // Additional functionality
}

In TypeName, you specify the class name or type you want to extend.


Now, let’s actually use an Extension to add functionality to the Date class.

We introduced how to convert a Date type into a formatted string in the article Convert Date to a Formatted String in Swift.

A simple conversion can be done with the following code:

import Foundation

let date = Date()

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"

print(df.string(from: date))

The output will be:

2023-08-16 20:14:00

Swift Extension example 1


Now let’s implement this as an Extension of the Date class:

extension Date {
    func toString(format: String) -> String {
        let df = DateFormatter()
        df.dateFormat = format
        return df.string(from: self)
    }
}

With extension Date { ... }, we are adding functionality to the Date class.

We define a toString function that takes a format string as an input parameter and returns a formatted string representation of the date.


Now, by using this function defined in the Extension, you can get a formatted string from a Date variable like this:

date.toString(format: "yyyy-MM-dd HH:mm:ss")

Let’s run the following code:

import Foundation

extension Date {
    func toString(format: String) -> String {
        let df = DateFormatter()
        df.dateFormat = format
        return df.string(from: self)
    }
}

let date = Date()
let dateStr = date.toString(format: "yyyy-MM-dd HH:mm:ss")

print(dateStr)

The output will be:

2023-08-16 20:25:26

Swift Extension example 2


As you can see, by using the function defined in the Extension, you can obtain a formatted string directly from a Date variable.


That wraps up our explanation of Extensions in Swift.