Home
Swift
swap Example (Swap Variables)
This page was last reviewed on Jan 13, 2024.
Dot Net Perls
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.
inout
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.
var
Step 1 We declare and initialize 2 strings, using the "var" keyword to allow the strings to be reassigned.
Step 2 We pass the strings as references to the swap method. This changes the values the strings are assigned to.
Step 3 The swap() function can be used on any 2 variables of the same type—here we use Ints.
Step 4 Again, the two variables now have the opposite value. No complicated if-statements were needed.
if
// 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.
This page was last updated on Jan 13, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.