How do I shuffle an array in Swift?


In this article, you will learn how to shuffle an array in the Swift language.

In Swift, you can use the shuffle() and shuffled() methods to shuffle the array elements.

shuffle()

The shuffle() method shuffles the elements of the collection in place, so the original array is modified.

shuffled()

If you want to create a shuffled copy of the array instead of modifying the original array, you can use the shuffled() method from the Sequence protocol.

Here is an example of how to use shuffle() to shuffle the array elements

Algorithm

  • Step 1 - Create an input array

  • Step 2 - Call the shuffle() function on the input array

  • Step 3 - This method modifies the original array

Example

import Foundation
var languages: [String] = ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
print("Original array = ",languages)
languages.shuffle()
print("Shuffle array = ",languages)

Output

Original array =  ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
Shuffle array =  ["Java", "GoLang", "JavaScript", "Python", "Swift", "PHP"]

Note that the order of the elements is random.

Here is an example of how to use shuffled() to shuffle the array elements

Algorithm

  • Step 1 - Create an input array

  • Step 2 - Call the shuffled() function on the input array

  • Step 3 - This method returns a new array

Example

import Foundation
var languages: [String] = ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
print("Original array = ",languages)
let shuffledLanguages = languages.shuffled()
print("Shuffle array = ",shuffledLanguages)

Output

Original array =  ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
Shuffle array =  ["PHP", "GoLang", "JavaScript", "Swift", "Python", "Java"]

Note that the order of the elements is random.

Conclusion

Both shuffle() and shuffled() use the default random number generator provided by the Foundation framework. If you need more control over the randomization process, you can use other randomization methods or create your own random number generator.

Updated on: 07-Sep-2023

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements