Back to Blog

Swift: Swap elements in array

Sandy LaneSandy Lane

Video: Swift: Swap elements in array by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift: Swap Elements in an Array

Swapping elements in an array is a common task when manipulating collections in Swift. This example demonstrates how to exchange the positions of two elements using Swift's built-in swapAt(_: _:) method, which efficiently swaps values in place without needing a temporary variable.

Code

var numbers = [10, 20, 30, 40, 50]

// Swap the elements at index 1 and index 3
numbers.swapAt(1, 3)

// numbers is now [10, 40, 30, 20, 50]
print(numbers)  // Output: [10, 40, 30, 20, 50]

Key Points

  • Use the swapAt(_:_) method to swap two elements in an array by their indices efficiently.
  • Swapping modifies the array in place without creating a new array or using extra memory for temporary storage.
  • Ensure the indices provided to swapAt are valid to avoid runtime errors.
  • This method works on any mutable collection conforming to MutableCollection, not just arrays.