How to Shuffle an Array in Swift
This tutorial is part of the Swift series.
Suppose you have an array in Swift, like this:
1 | var items = 1...3 |
and you want to shuffle the items in random order.
There are two ways to accomplish this in Swift.
Mutating the Original Array
One way is by using the shuffle()
method, which shuffles the items in the array:
1 | items.shuffle() |
Note that the array is declared using var
because arrays are structs and declaring it with let
would make it immutable, resulting in an error.
Creating a New Shuffled Array
Another way is by using the shuffled()
method, which does not mutate the original array but instead returns a new shuffled array:
1 | let items = 1...3 |
In this case, it is safe to declare the variables using let
since the shuffled()
method does not modify the original array.
Tags: swift, array shuffling, shuffle method.