Swift
Array
Programming
Elements
Tutorial

How to exchange elements in swift array?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Swapping two elements in a Swift array is a small operation, but it appears constantly in sorting, shuffling, and many in-place algorithms. Swift already provides the right tool for this: swapAt. Using the built-in method is clearer and safer than manually moving values around in most cases.

Use swapAt for Direct Element Exchange

The standard way to exchange two elements is:

swift
1var numbers = [10, 20, 30, 40]
2numbers.swapAt(1, 3)
3
4print(numbers) // [10, 40, 30, 20]

swapAt mutates the array in place. That means the array must be declared with var, not let.

It also uses indices, so the positions must be valid for the array.

Why swapAt Is Better Than Manual Swapping

You can swap manually with a temporary variable:

swift
1var letters = ["a", "b", "c"]
2
3let temp = letters[0]
4letters[0] = letters[2]
5letters[2] = temp
6
7print(letters) // ["c", "b", "a"]

That works, but swapAt expresses intent more directly:

swift
var letters = ["a", "b", "c"]
letters.swapAt(0, 2)
print(letters) // ["c", "b", "a"]

The second version is shorter, easier to read, and less error-prone.

Check Indices Before Swapping

Like any indexed array access, swapAt will trap at runtime if either index is out of bounds. If the indices come from user input or algorithmic calculations, validate them first.

swift
1func safeSwap<T>(_ array: inout [T], _ first: Int, _ second: Int) {
2    guard array.indices.contains(first), array.indices.contains(second) else {
3        return
4    }
5
6    array.swapAt(first, second)
7}
8
9var values = [1, 2, 3]
10safeSwap(&values, 0, 2)
11print(values) // [3, 2, 1]

This pattern is useful when invalid indices are possible and you want to avoid a crash.

Swapping With Generic Code

Because arrays in Swift are generic collections, you can build reusable helpers that work with any element type.

swift
1func exchange<T>(in array: inout [T], at first: Int, and second: Int) {
2    array.swapAt(first, second)
3}
4
5var names = ["Ada", "Grace", "Linus"]
6exchange(in: &names, at: 0, and: 2)
7print(names) // ["Linus", "Grace", "Ada"]

This does not add functionality beyond swapAt, but it can improve readability if your domain language prefers names such as exchange or moveEndpoints.

Understand Value Semantics

Swift arrays are value types. When you pass an array normally, you pass a value, not a shared mutable object. If you want a helper function to mutate the original array, use inout.

swift
1func reverseFirstTwo(_ array: inout [Int]) {
2    array.swapAt(0, 1)
3}
4
5var data = [5, 6, 7]
6reverseFirstTwo(&data)
7print(data) // [6, 5, 7]

Without inout, the function would modify only its local copy.

Swapping Is Common in Algorithms

Many in-place algorithms depend on swapping. A simple example is selection sort:

swift
1func selectionSort(_ array: inout [Int]) {
2    for i in 0..<array.count {
3        var minIndex = i
4
5        for j in (i + 1)..<array.count {
6            if array[j] < array[minIndex] {
7                minIndex = j
8            }
9        }
10
11        if i != minIndex {
12            array.swapAt(i, minIndex)
13        }
14    }
15}
16
17var numbers = [64, 25, 12, 22, 11]
18selectionSort(&numbers)
19print(numbers) // [11, 12, 22, 25, 64]

This is a good example of why clear swap operations matter. The algorithm is easier to understand when the exchange step is explicit.

What Happens If the Indices Are Equal

If you call swapAt with the same index twice, Swift simply leaves the array unchanged.

swift
var items = [1, 2, 3]
items.swapAt(1, 1)
print(items) // [1, 2, 3]

That behavior is useful because you usually do not need a separate special case when an algorithm happens to choose the same position for both sides of the swap.

Common Pitfalls

The biggest mistake is using invalid indices and causing a runtime trap. Another is declaring the array with let, which makes it immutable and impossible to swap in place. Developers also sometimes write manual temp-variable code when swapAt would be clearer. In helper functions, forgetting inout means the original array does not change. Finally, if you are swapping based on values rather than indices, you still need to find valid positions first before calling swapAt.

Summary

  • Use swapAt as the standard way to exchange two elements in a Swift array.
  • The array must be mutable, so declare it with var.
  • Validate indices when they are not guaranteed to be safe.
  • Use inout in helper functions that need to mutate the caller’s array.
  • 'swapAt keeps algorithms such as sorting code clearer than manual temp-variable swaps.'
  • Swapping the same index with itself is valid and leaves the array unchanged.

Course illustration
Course illustration

All Rights Reserved.