🎓 A1Learner
🔍
0 of 36 lessons completed

Swift Generic Functions

A generic function is a function that works with a placeholder type instead of one fixed type. Each call fills the placeholder with the type of the values it passes.

The same swap written twice

The swapInts function swaps two Int values, and swapWords repeats the same steps for two String values. Only the type changes between the two functions.

func swapInts(_ first: inout Int, _ second: inout Int) {
    let held = first
    first = second
    second = held
}
func swapWords(_ first: inout String, _ second: inout String) {
    let held = first
    first = second
    second = held
}
var firstNumber = 1
var secondNumber = 2
swapInts(&firstNumber, &secondNumber)
print(firstNumber)
print(secondNumber)
var firstWord = "red"
var secondWord = "blue"
swapWords(&firstWord, &secondWord)
print(firstWord)
print(secondWord)

One generic swap

The swapValues function uses the placeholder T in place of a fixed type. The same one function now swaps the numbers and then the words.

func swapValues<T>(_ first: inout T, _ second: inout T) {
    let held = first
    first = second
    second = held
}
var firstNumber = 1
var secondNumber = 2
swapValues(&firstNumber, &secondNumber)
print(firstNumber)
print(secondNumber)
var firstWord = "red"
var secondWord = "blue"
swapValues(&firstWord, &secondWord)
print(firstWord)
print(secondWord)

Printing any array

The printItems function takes an array of the placeholder type and prints each element on its own line. It prints numbers first and words second, with no change to the function.

func printItems<T>(_ items: [T]) {
    for item in items {
        print(item)
    }
}
printItems([10, 20, 30])
printItems(["sun", "moon"])

Counting any array

The countItems function returns the count of an array of the placeholder type. It counts a number array and a word array with the same body.

func countItems<T>(_ items: [T]) -> Int {
    return items.count
}
print(countItems([4, 8, 15, 16]))
print(countItems(["ana", "bo"]))

Example

func pair<T>(_ first: T, _ second: T) -> String {
    return "\(first) and \(second)"
}
print(pair(3, 4))
print(pair("salt", "pepper"))

Key points

  • Writing the same function once per type repeats the same logic in several places.
  • A generic function writes the placeholder name inside angle brackets after the function name.
  • The placeholder stands for one real type within each call.
  • The same generic function can be called with values of different types in one program.
  • The compiler checks each call against the real type that fills the placeholder.

In this example, the pair function is generic over the placeholder T and joins two values of that type into one line of text. The first call fills T with Int and prints 3 and 4. The second call fills T with String and prints salt and pepper.

Note

The placeholder is not a real type that values are made from, and it is fixed separately for every call.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the <T> after a generic function name declare?