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

by The Captain

May 23, 2023

Swift Extensions

Swift extensions allow developers to add new functionality to an existing class, struct, or enumeration. This is incredibly powerful because it allows you to extend the functionality of types that you don't own - even types defined in Apple's frameworks.

Extensions can add:

  • New computed properties and computed type properties
  • New instance and type methods
  • New subscripts
  • New initializers
  • New nested types

Here's an example of extending the Int type to add a new computed property that returns a string representation of the number with commas:

extension Int {
    var commaFormatted: String {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        return numberFormatter.string(from: NSNumber(value:self)) ?? ""

let aNumber = 1000000
let result = aNumber.commaFormatted // "1,000,000"

In the code above, we're adding a new computed property called commaFormatted to the Int type. This property uses a NumberFormatter to create a string with commas for large numbers.

The extension is defined using the extension keyword followed by the name of the type being extended, Int in this case. The computed property is defined inside the curly braces that follow.

Extensions can also be used to group related functionality together:

extension String {
    func capitalizingFirstLetter() -> String {
        prefix(1).capitalized + dropFirst()
    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()

var greeting = "hello world"
greeting.capitalizeFirstLetter() // "Hello world"

In this example, we're extending the String type to add two methods that capitalize the first letter of the string.

The first method is capitalizingFirstLetter, which returns a new string with the first letter capitalized. The second method is capitalizeFirstLetter, which modifies the string in place by calling the first method and assigning the result back to the original variable.

Using extensions to add functionality to existing types can simplify code and make it easier to read and understand.