- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.