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.
collection.swapAt(i,j)
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 with i
.
Note: When the index specified is beyond the length of the collection, an error is thrown.
The method returns the same collection, but with the specified elements swapped.
// 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)
0
with the element at the index position 1
.2
with the element at the index position 4
.