swapAt() method is used to swap elements in different positions of a collection. It exchanges the values at the specified indexes of the collection.
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
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 collections var names = ["Theodore", "Mary", "Jame"] var gnaam = ["Google", "Netflix", "Meta", "Apple", "Amazon"] // swap elements names.swapAt(0,1) gnaam.swapAt(2,4) // print results print(names) print(gnaam)
0with the element at the index position
2with the element at the index position
View all Courses