Array random shuffle in Swift with example

Array elements are ordered based on the insertion order of elements.

The elements can be retrieved on the index.

Sometimes, array elements shuffle randomly and access it using an index.

The shuffle an array means, the elements in the original array reset their’ position randomly

There are many ways we can do it.

Swift Array Shuffle example

Swift 4 version provides two methods.

  • shuffle method: This shuffles elements in random order by modifying the original array. It is also called the mutable shuffle method.
  • shuffled method This shuffles elements in random order without modifying the original array. It is also called the immutable shuffle method.

Array mutable shuffle method example

var numbers=[11, 12, 13, 21, 22, 23]
print(numbers);
numbers.shuffle();
print(numbers);

Output:

[11, 12, 13, 21, 22, 23]
[12, 21, 11, 22, 13, 23]

Array immutable shuffled method example

var numbers=[11, 12, 13, 21, 22, 23]
print(numbers);
var numbers1=numbers.shuffled();
print(numbers1);

Output:

[11, 12, 13, 21, 22, 23]
[11, 13, 22, 23, 21, 12]

Another way of writing using custom logic.

Generate the random index and returns the random elements.

Int type contains a random method, so generate random numbers between zero and array count. It returns a random index and gets the element from an array using this index.

You can check the post on multiple ways to Generate Random numbers

var numbers=[11, 12, 13, 21, 22, 23]
let randomIndex = Int.random(in: 0..<numbers.count)
print(numbers[randomIndex]);

let randomIndex1 = Int.random(in: 0..<numbers.count)
print(numbers[randomIndex1]);

let randomIndex2 = Int.random(in: 0..<numbers.count)
print(numbers[randomIndex2]);

Output:

23
21
23