Back to Blog

Swift: Swap random elements in array

Sandy LaneSandy Lane

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

Watch full page →

Swift: Swap Random Elements in an Array

Swapping two random elements in a Swift array is a useful technique when you want to shuffle or randomly reorder parts of your data. This example demonstrates how to safely pick two distinct random indices and swap their values within the array.

Code

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

// Ensure the array has at least two elements to swap
if numbers.count > 1 {
  // Pick two distinct random indices
  var firstIndex = Int.random(in: 0 ..< numbers.count)
  var secondIndex = Int.random(in: 0 ..< numbers.count)
  
  // Repeat until the indices are different
  while secondIndex == firstIndex {
    secondIndex = Int.random(in: 0 ..< numbers.count)
  }
  
  // Swap the elements at the two indices
  numbers.swapAt(firstIndex, secondIndex)
}

print(numbers)  // The array with two elements swapped randomly

Key Points

  • Use Int.random(in:) to generate random indices within the array bounds.
  • Ensure the two indices are distinct to avoid swapping an element with itself.
  • The swapAt(_:_:) method efficiently swaps elements at two indices in-place.
  • Check the array has at least two elements before attempting to swap.