How to shuffle array elements in Swift

In this Swift programming tutorial, we will learn how to shuffle array elements in multiple ways.

Sometimes while developing any application in Swift, we may need to shuffle or randomize the array of elements.
To achieve this, Swift provides two built-in methods to shuffle any given array. These methods rearrange the elements of an array in random order. Those two methods are:

  • shuffle()
  • shuffled()

Let’s discuss each of the methods in detail.

Using shuffle() method

The shuffle() method shuffles the elements in the original array itself. To be clear, it modifies the original array by randomly rearranging the elements.

Syntax:
array.shuffle()

While using this method, we must declare the array using the varĀ keyword, so that the array can be mutable. Otherwise, if we declare using the let keyword, it raises an error since it creates an immutable array.

Swift program to shuffle given array using shuffle() method:

var arr=[1,2,3,4,5,6,7]
arr.shuffle()
print("The array after shuffling:",arr)

Output:

The array after shuffling: [4, 3, 5, 1, 7, 2, 6]

In the above program, we first created an integer array arr using the var keyword. Then we applied the shuffle() method to that array. As a result, we can observe that our array got shuffled when it is printed.

Using shuffled() method

The shuffled() method returns a new shuffled array which can be stored in some variable. We can use this method if we want to have separate original and shuffled arrays. So that we can reuse the original array for other purposes.

Syntax:
array.shuffled()

The only difference between these two methods is that the shuffle() method shuffles the array itself. Whereas the shuffled() method returns a new shuffled array.

Since we are not modifying our original array, we can declare it using either let or var keywords.

Swift program to shuffle given array using shuffled() method:

let arr=[1,2,3,4,5,6,7]
var k=arr.shuffled()
print("The array after shuffling:",k)

Output:

The array after shuffling: [6, 1, 7, 3, 5, 4, 2]

In the above program, we can also use the var keyword to declare the original array arr. After using the shuffled() method, it returned the shuffled array which is stored in variable k.

That’s it! Hope you understood how to shuffle array elements in Swift.

Also read,

Leave a Reply

Your email address will not be published.