Swift shuffle() and shuffled() methods

The shuffle() and shuffled() methods are two in-built methods of Swift. Both these methods can shuffle a collection. These methods can help us to reorder the elements of a collection.

Though both methods use to shuffle a collection type, there is a difference between them.

The shuffle() method shuffles the collection in place. That means it modifies the collection.

On the other hand, the shuffled() method doesn’t modify the existing collection, it returns a new collection in which the element of the existing collection is shuffled.


Syntax of shuffle() method:

Below is the given syntax for the shuffle() method:


Syntax of shuffled() method:

The syntax for the Swift shuffled() method is given below:


Example of Swift shuffle()

Below is given an example of using the shuffle() method to shuffle the elements of an array:

var myNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]




[2, 6, 0, 1, 5, 3, 4, 8, 7, 9]

In the above, you can see that we have created a variable to store our array instead of using a constant. If we use constant, then using the shuffle() method will return an error because the shuffle() method will not be able to modify the array.

In the output, we can see that the elements of our array reorder.

Example of Swift shuffled()

In the example below, you can see the usage of the Swift shuffled() method:

let myNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

let shuffledNumbers = myNumbers.shuffled()



[2, 1, 0, 4, 8, 3, 5, 7, 9, 6]

In the above code, we have used the shuffle() method that creates a new array with all the elements of the existing array but the elements reordered.

Also, read: