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 with i.

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 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)

Code explanation

  • Lines 2–3: We create some arrays.
  • Line 6: We swap the element at the index position 0 with the element at the index position 1.
  • Line 7: We swap the element at the index position 2 with the element at the index position 4.
  • Lines 10–11: We print the results to the console.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources