Sling Academy
Home/Swift/Swift: 4 Ways to Shuffle an Array

Swift: 4 Ways to Shuffle an Array

Last updated: April 19, 2023

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.

Next Article: Swift Array.allSatisfy() Method: Tutorial & Examples

Previous Article: Swift array filter(): Tutorial & examples

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)