Published Jul 6, 2023
Contribute to Docs

The .shuffle() method in Swift is used to randomly shuffle the elements of an array. It reorders the elements in a random order, providing a different arrangement of the elements each time it is called.


The syntax of the .shuffle() method is as follows:


The arrayName is the name of the array to shuffle. The method will shuffle the elements of the array in place: it modifies the original array in lieu of returning a copy.


A basic implementation of the .shuffle() method is demonstrated below:

var numbers = [1, 2, 3, 4, 5]

The output will be something similar to:

[4, 1, 2, 5, 3]

Each time the code is executed, the output will be different since the elements are shuffled randomly.

The .shuffle() method provides a convenient way to introduce randomness into the order of elements in an array, which can be useful for various scenarios like randomizing game elements, shuffling a playlist, or generating random sequences.

Note: The .shuffle() method is available in Swift 4.2 and later versions.

All contributors

Looking to contribute?

Learn Swift on Codecademy