Swap. 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.
Syntax note. Swap receives references (inout) to 2 variables—if we do not provide the reference operator we will receive a compile-time error.
Example. 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.
// 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
Inout error. 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 '&'
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.