How to swap array items to different positions in Swift
Overview
The swapAt() method is used to swap elements in different positions of a collection. It exchanges the values at the specified indexes of the collection.
Syntax
collection.swapAt(i,j)
Parameters
-
i: This is the index of the first value that we want to swap. It must be an integer. -
j: This is the index of the second value that we want to swap withi.
Note: When the index specified is beyond the length of the collection, an error is thrown.
Return value
The method returns the same collection, but with the specified elements swapped.
Code example
// create array collectionsvar names = ["Theodore", "Mary", "Jame"]var gnaam = ["Google", "Netflix", "Meta", "Apple", "Amazon"]// swap elementsnames.swapAt(0,1)gnaam.swapAt(2,4)// print resultsprint(names)print(gnaam)
Code explanation
- Lines 2–3: We create some arrays.
- Line 6: We swap the element at the index position
0with the element at the index position1. - Line 7: We swap the element at the index position
2with the element at the index position4. - Lines 10–11: We print the results to the console.