Swapping two array elements in Swift is piece of cake, as Swift has a global swap function which works with any data type. Even better, this simple code example will introduce how In-Out parameters work and provide a glimpse into a generic function.
Let’s start with the code to swap two array elements:
var arrayStrings = ["123", "456", "789"] var arrayInts = [1, 2, 3] println("String array: \(arrayStrings)") swap(&arrayStrings, &arrayStrings) println("Updated string array: \(arrayStrings)") println("\nInt array: \(arrayInts)") swap(&arrayInts, &arrayInts) println("Updated int array: \(arrayInts)")
Couldn’t be easier. Here’s the output:
String array: [123, 456, 789]
Updated string array: [789, 456, 123]
Int array: [1, 2, 3]
Updated int array: [3, 2, 1]
Generic Functions and InOut Parameters in Swift
To get an idea what’s going on here, let’s look at the definition of the swap function:
func swap<T>(inout a: T, inout b: T)
The T inside the angle brackets indicates a placeholder that any data type can be provided. However, notice that the two values passed in (a and b) must both be of type T (that is, both must be the same type). T is known as a type parameter, and the choice of T is arbitrary. Although the Swift documentation states that it is traditional to use T, it is not required when defining your own generic functions.
In Swift, by default, parameters passed to a function by value, that is, a copy is provided to the function. If you want a function to modify a parameter, you must define the parameter as an ‘inout’ parameter, hence the inout reference in the swap function definition. When the function is called, the value(s) are passed to the function are modified and passed back replacing the original value(s).
When you call a function with an inout parameter(s), you use an ampersand (&) as shown in the code on lines 4 and 7. In C this is referred to as passing the address of the value, not a copy of the value. Although the Swift documentation doesn’t state this in the same manner, the idea is the equivalent.
In a future post I’ll dive into more details of both inout parameters and generic functions.