In Swift, we can use two methods to shuffle an array:
shuffle
shuffled
Both the shuffle
and shuffled
methods reorder the elements of an array randomly.
When we use the shuffle
method, the elements are shuffled in-place. shuffle
happens in the original array.
When we use the shuffled
method, the elements are shuffled and returned as a new array. The old array remains untouched.
import Swiftvar numbers = [Int](1...5)print("The array is :- \(numbers)")print("Shuffling array")numbers.shuffle()print(numbers)
In the above code, we have created an array numbers
with five items and called the shuffle()
method to shuffle the array’s items in place. Now, when we print the number
array, the numbers
array elements will be shuffled.
import Swiftvar numbers = [Int](1...5)print("The array is :- \(numbers)")var shuffledArray = numbers.shuffled()print("\nAfter Shuffling array the value of Array -> \(numbers)")print("\nAfter Shuffling array the value of shuffled Array -> \(shuffledArray)")
In the code above, we have created a numbers
array with five items and called the shuffled()
method to shuffle the array’s items. The shuffled
method will shuffle and return a new array. The numbers
array remains unchanged. We then print it to check the order of numbers
and shuffledArray
.