Generic functions

Let's begin by examining the problem that generics try to solve and then we will see how generics solve this problem. Let's say that we wanted to create functions that swapped the values of two variables (as described in the introduction); however, for our application, we have a need to swap two ints, two doubles, and two strings. Without generics, this would require us to write three separate functions. The following code shows what these functions would look similar to:

func swapInts (inout a: Int, inout b: Int) {
    let tmp = a
    a = b
    b = tmp
}

func swapDoubles(inout a: Double, inout b: Double) {
    let tmp = a
    a = b
    b = tmp
}

func swapStrings(inout a: String, inout b: String) {
    let tmp = a
    a = b
    b = tmp
}

With these three functions, ...

Get Swift: Developing iOS Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.