Generics. Part 1

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.

Generics are one of the most powerful features of Swift, and much of the Swift standard library is built with generic code. In fact, you’ve been using generics throughout the Language Guide, even if you didn’t realize it. For example, Jazz Array and Map types both is generic collections. You can create an array that holds int values, or an array that holds String values, or indeed an array for any other type that can be created in Jazz. Similarly, you can create a Map to store values of any specified type, and there are no limitations on what that type can be.

The Problem That Generics Solve

Here’s a standard, non generic function called swapTwoInts, which swaps two int values:

fun swapTwoInts(x: int*,y: int*) {
    var temp = x;
    *x = *y;
    *y = *temp;
}

The swapTwoInts function is useful, but it can only be used with int values. If you want to swap two String values, or two float64 values, you have to write more functions, such as the swapTwoStrings and swapTwoFloats functions shown below:

fun swapTwoFloats(x: float64*,y: float64*) {
    var temp = x;
    *x = *y;
    *y = *temp;
}

fun swapTwoStrings(x: String*,y: String*) {
    var temp = x;
    *x = *y;
    *y = *temp;
}

You may have noticed that the bodies of the swapTwoInts, swapTwoStrings, and swapTwoFloats functions are identical. The only difference is the type of the values that they accept (int,String and float64).

It’s more useful, and considerably more flexible, to write a single function that swaps two values of any type. Generic code enables you to write such a function. (A generic version of these functions is defined in Generics. Part 2)

Last updated