Swift: 3 Ways to Swap 2 Elements in an Array

Updated: April 19, 2023 By: Khue Post a comment

Swapping 2 array elements means exchanging their positions in the array. For example, if you have an array like [1, 2, 3, 4] and you want to swap the elements at index 0 and index 2, you will get [3, 2, 1, 4] after swapping. This concise, straight-to-the-point article will show you 3 different ways to swap 2 array elements in Swift.

Using the swapAt() method

This method takes two indices as arguments and swaps the values at those indices. Note that it will make changes to the input array.

Example:

var myArray = ["a", "b", "c", "d", "e"]
print("Initial Array:", myArray)

// swap the values at index 2 and 3
myArray.swapAt(2, 3) 

print("Array after swapping:", myArray)

Output:

Initial Array: ["a", "b", "c", "d", "e"]
Array after swapping: ["a", "b", "d", "c", "e"]

Using tuple assignment

The tuple assignment allows you to assign multiple values at once. Therefore, it can help us swap array elements easily. The general syntax is:

(array[index1], array[index2]) = (array[index2], array[index1])

Example:

var words = ["Sling", "Academy", "Swift", "iOS", "Developer"]
print("Initial Array:", words)

// swap the values at index 1 and 4
(words[1], words[4]) = (words[4], words[1])
print("Array after swapping:", words)

Output:

Initial Array: ["Sling", "Academy", "Swift", "iOS", "Developer"]
Array after swapping: ["Sling", "Developer", "Swift", "iOS", "Academy"]

Using temporary variables

Using temporary variables for swapping array elements is widely used in many programming languages including Swift. You can assign the value of one element to a temporary variable, then assign the value of another element to the first element, and then assign the value of the temporary variable to the second element.

Example:

var letters = ["A", "B", "C", "D", "E"]
print("Initial Array:", letters)

// store the value of the element at index 2 in a temporary variable
var temp = letters[2] 

// assign the value of the element at index 3 to the element at index 2
letters[2] = letters[3] 

// assign the value of the temporary variable to the element at index 3
letters[3] = temp 
print("Array after swapping:", letters)

Output:

Initial Array: ["A", "B", "C", "D", "E"]
Array after swapping: ["A", "B", "D", "C", "E"]

In Swift, using temporary variables for swapping array elements is not very concise or elegant. Consider using one of the preceding approaches such as swapAt() or tuple assignment to achieve the same result with less code and more clarity.

If you have any questions or want to learn more about functions or Swift programming language, feel free to leave a comment. Happy coding & have a nice day!