Swap two elements of an array in Swift


In this Swift programming tutorial, you will learn how to swap two elements of an array with the help of examples.

To swap two array items, you can use the swapAt() method.

Below is the code:

var numbers = [3, 5, 7, 8, 11]

print("Initial Array:", numbers)

numbers.swapAt(2, 3)

print("Array after swapping:", numbers)

Output:

Initial Array: [3, 5, 7, 8, 11]
Array after swapping: [3, 5, 8, 7, 11]

As you can see in our above example, we have alternated the position of two elements from our Swift array. Notice the output result, you can see that the position of the values 7 and 8 have been swaped.

Now let’s see another example:

var colors = ["Black", "Yellow", "Green"]

print("Initial Array:", colors)

colors.swapAt(0, 2)

print("Array after swapping:", colors)

Below is the given output for the above code:

Initial Array: ["Black", "Yellow", "Green"]
Array after swapping: ["Green", "Yellow", "Black"]