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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.