Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 like:

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, we can swap the original values of two ints, two doubles, and two strings. Now, let's say, as we develop our application further, we find out that we also need to swap the values of two UInt32, two floats, or even...