Shuffling an array means randomly re-arranging the elements of that array. This example-based, practical article will walk you through several different ways to shuffle a given array in Swift.
Using the shuffle() method
The shuffle() method randomly reorders the elements of an array. It modifies the original array, so you don’t need to assign the result to a new variable.
Example:
var numbers = [1, 2, 3, 4, 5]
numbers.shuffle()
print(numbers)
My output:
[1, 3, 4, 5, 2]
Due to the randomness, the result is not consistent.
Using the shuffled() method
The shuffled() method (don’t be confused with the shuffle() method in the preceding section) returns a new array with the elements of the original array shuffled. It does not modify the original array, so you need to assign the result to a new variable.
Example:
let letters = ["a", "b", "c", "d", "e"]
let shuffledLetters = letters.shuffled()
print(shuffledLetters)
Output:
["a", "d", "b", "e", "c"]
Using a for loop
Another solution is to use a loop to iterate over the array and swap each element with a random element. This is also known as the Fisher-Yates algorithm.
Example:
var array = [1, 2, 3, 4, 5]
// Loop from the last element to the second one
for i in stride(from: array.count - 1, to: 0, by: -1) {
// Pick a random index from 0 to i
let j = Int.random(in: 0 ... i)
// Swap the elements at i and j
array.swapAt(i, j)
}
print(array)
Output:
[1, 4, 3, 5, 2]
This technique works well, but it seems too long than necessary. It’s useful for learners but if you are developing real-world apps, consider using one of the two first built-in methods.
Generating random indices
An alternative possible solution is to use an iterator that generates random indices and use it to swap the elements of the array.
Example:
var array = [1, 2, 3, 4, 5]
// Create an iterator that generates random indices
let iterator = AnyIterator { Int.random(in: 0 ..< array.count) }
// Loop over the array using the iterator
for (i, _) in zip(array.indices, iterator) {
// Swap the element at i with a random element
array.swapAt(i, iterator.next()!)
}
print(array)
Output:
[5, 1, 4, 2, 3]
Like the previous approach, this one seems too verbose when compared to the shuffle() or shuffled() method.