W1351 Swap Function
Prerequisites[edit]
Introduction[edit]
A very common need in many algorithms is swapping the values in two variables. It's also very common that these two variables are contained within an array.
Swapping[edit]
The first approach that most students take when swapping is this:
let x = 5
let y = 7
x = y
y = x
Take the time to think through what you believe will occur as the above code is executed. Then, try it.
![]() |
Observe, Ponder, and Journal Section 1 |
|
The primary issue that most students encounter in this scenario is overwriting the value of one of the variables, and then assigning this overwritten value to the other variable.
![]() |
Observe, Ponder, and Journal Section 2 |
Assuming that the syntax errors in the above code segment are resolved:
|
View the following video: Swapping Algorithm (YouTube)
![]() |
Observe, Ponder, and Journal Section 3 |
|
Functions Which Modify Their Arguments[edit]
If we want to modify the value of a (value-type) argument passed to a function, a special syntax is required. Consider the following code segment:
func increment(n:Int) {
n = n + 1
}
var x = 7
increment(n:x)
print(x)
![]() |
Observe, Ponder, and Journal Section 4 |
|
Swift protects us from common errors by ensuring that a (value-type) argument passed to a function cannot be altered by a function except under specific circumstances. When (in generally rare cases) this is desirable, a special syntax is required:
- We must ensure that the function declaration specifies that this function is enabled to modify a specific argument
- Whenever we invoke the function, the function invocation must also specify that the specific argument may be modified
This strategy ensures that we don't accidentally modify function arguments.
An example will serve to clarify:
func increment(n:inout Int) {
n = n + 1
}
var x = 7
increment(n:&x)
print(x)
![]() |
Observe, Ponder, and Journal Section 5 |
|
![]() |
Going Deeper |
Technically, the inout keyword specifies that the argument will be an L-Value. Refer to [W1038 L-Values and R-Values]. |
Exercises[edit]
![]() |
Exercises |
|