Swift Array swapAt()

The swapAt() method swaps two elements at the specified indices of the array.

Example


swapAt() Syntax

The syntax of the array swapAt() method is:

array.swapAt(index1: Int, index2: Int)

Here, array is an object of the Array class.


swapAt() Parameters

The swapAt() method takes two parameters:

  • index1 - index of the first element to swap
  • index2 - index of the second element to swap

swapAt() Return Value

The swapAt() method doesn't return any value. It only swaps elements of the current array.


Example 1: Swift Array swapAt()

Output

["Swift", "Java", "C"]
[35, 21, 12]

Here,

  • For the languages array, we have swapped the elements of index 1 and index 2.
  • Similarly, for the priceList array, we have swapped the elements of index 0 and index 2.