TExcelTAD
Home › Swift › Swift Extensions

Swift Extensions

An extension adds new functionality to an existing type — even one you didn't write, like Int or String. You don't need the original source code and you don't create a subclass: the new members simply become part of the type everywhere in your module.

Extending a built-in type

swift · try it yourself
extension Int {
    var isEven: Bool { self % 2 == 0 }

    func squared() -> Int { self * self }

    func times(_ action: () -> Void) {
        for _ in 0..<self { action() }
    }
}

print(7.isEven, 10.isEven)
print(12.squared())
3.times { print("Swift!") }
false true
144
Swift!
Swift!
Swift!

Inside the extension, self is the value the member is called on — here an Int.

What an extension can add

Can add Cannot add
Computed properties (instance and static) Stored instance properties
Instance and type methods Overrides of existing members
mutating methods for value types Designated initializers on classes
New initializers (convenience inits for classes) Property observers on existing properties
Subscripts and nested types
Protocol conformances

The "no stored properties" rule exists because adding storage would change the memory layout of a type that might already be in use.

Adding initializers without losing the memberwise one

As you saw in the Initializers lesson, writing an init inside a struct removes its free memberwise initializer. Putting the extra initializer in an extension keeps both:

swift · try it yourself
struct Color {
    var red: Int
    var green: Int
    var blue: Int
}

extension Color {
    init(gray: Int) {
        self.init(red: gray, green: gray, blue: gray)
    }

    static let black = Color(gray: 0)

    var hex: String {
        let digits = Array("0123456789ABCDEF")
        func pair(_ v: Int) -> String { "\(digits[v / 16])\(digits[v % 16])" }
        return "#" + pair(red) + pair(green) + pair(blue)
    }
}

print(Color(red: 240, green: 81, blue: 56).hex)   // memberwise still works
print(Color(gray: 128).hex)
print(Color.black.hex)
#F05138
#808080
#000000

Mutating methods and subscripts

Extensions on value types can add mutating methods and subscripts:

swift · try it yourself
extension String {
    mutating func shout() {
        self = uppercased() + "!"
    }

    // safe character lookup by Int position
    subscript(at offset: Int) -> Character? {
        guard offset >= 0, offset < count else { return nil }
        return self[index(startIndex, offsetBy: offset)]
    }
}

var word = "hello"
word.shout()
print(word)
print(word[at: 1] ?? "-", word[at: 50] ?? "-")
HELLO!
E -

Adding protocol conformance

A very common pattern is to keep a type's core definition small and add each protocol conformance in its own extension. This groups related code together:

swift · try it yourself
struct Money {
    let cents: Int
}

extension Money: CustomStringConvertible {
    var description: String {
        let dollars = cents / 100
        let rest = cents % 100
        return "$\(dollars).\(rest < 10 ? "0" : "")\(rest)"
    }
}

extension Money: Comparable {
    static func < (a: Money, b: Money) -> Bool { a.cents < b.cents }
}

let prices = [Money(cents: 1999), Money(cents: 505), Money(cents: 1200)]
print(prices.sorted())
print("Most expensive:", prices.max()!)
[$5.05, $12.00, $19.99]
Most expensive: $19.99

Constrained extensions

With a where clause, an extension only applies when a condition holds — for example, only to arrays whose elements are numbers:

swift · try it yourself
extension Array where Element: Numeric {
    func total() -> Element {
        reduce(0, +)
    }
}

print([1, 2, 3, 4].total())
print([0.5, 1.25].total())
// ["a", "b"].total() would not compile: String is not Numeric
10
1.75

Tip: Organise large types with extensions and a comment marker: // MARK: - Networking. Xcode shows these markers in its jump bar.

Note: If two extensions (for example from two libraries) add a member with the same name to the same type, the compiler reports an ambiguity. Give extension members on popular types distinctive names.

Test yourself

Which of these can an extension NOT add?

  1. A computed property
  2. A method
  3. A stored instance property
  4. Protocol conformance

Why put a struct's custom init in an extension?

  1. It runs faster
  2. The struct keeps its automatic memberwise initializer
  3. Extensions cannot contain initializers
  4. To make it failable

What does extension Array where Element: Numeric do?

  1. Adds members to every array
  2. Adds members only to arrays whose elements are numeric
  3. Makes arrays numeric
  4. Creates a new Array type