In this tutorial, I will let you know how to shuffle an array in Swift programming. Shuffling of an array means randomizing the order of its elements.
Swift already has two built-in methods that can help us to shuffle elements of an array. Below are given the methods that I am talking about:
shuffled methods can help us randomize the element’s order, but there is a difference.
If we use the
shuffle() method, the elements are shuffled in-place. That means, the element’s order of the original array changed and thus the array will be changed.
On the other hand, if we use the
shuffled() method, it will not change the original array. Instead of changing the element order of the original array, it generates a new array. The old array remains unchanged.
Below is an example of using the shuffle method:
import Swift var myArray = [1,2,3,4,5] myArray.shuffle() print(myArray)
[4, 2, 5, 1, 3]
In your case, most probably, the elements will be in a different order when you run the code on your machine. Every time we run the code, it will change the order of the elements. You can see that we are printing the original array. That proves that the original array changed the order of its elements.
Now let’s see the example of using the
shuffled method in Swift:
import Swift var myArray = [1,2,3,4,5] var shuffledArray = myArray.shuffled() print("Old array: \(myArray)") print("New array: \(shuffledArray)")
Old array: [1, 2, 3, 4, 5]
New array: [4, 3, 5, 1, 2]
In our example, we can see that the old array remains the same, but the new array changes the order of its elements. That’s how the shuffled method works.
In this example, we have printed both the old array and new array so that you can understand the role of the
shuffled method in a better way.
I hope, you have understood how you can shuffle a Swift array using shuffle and shuffled array. You can use one of these two methods depending on your needs.