Sometimes it is necessary to exchange the values within 2 variables—this may be useful within certain loops. In Swift 5.9, we can use the built-in swap()
function.
Swap receives references (inout) to 2 variables—if we do not provide the reference operator we will receive a compile-time error.
This Swift 5.9 program uses the built-in swap()
2 times, on different variable types. Please note that the variables were declared with the "var
" keyword.
var
" keyword to allow the strings to be reassigned.swap()
function can be used on any 2 variables of the same type—here we use Ints.if
-statements were needed.// Step 1: declare 2 Strings. var left = "left" var right = "right" // Step 2: swap the Strings and print them. swap(&left, &right) print(left, right) // Step 3: declare two Ints. var zero = 0 var one = 1 // Step 4: swap the Ints and print the swapped values. swap(&zero, &one) print(zero, one)right left 1 0
If we do use an ampersand when passing a variable, we will get a "passing value" error. This can be easily corrected with a single character.
programs\program.swift:9:6: error: passing value of type 'String' to an inout parameter requires explicit '&'
With the useful swap()
function, built into the Swift standard library, we can swap variables. This function sometimes allows to eliminate a cumbersome if
-statement.