O'Reilly logo

Mastering Swift 2 by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required