
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Shuffle Elements of an Array in Swift
Swift provide an in built function named as shuffle() to shuffle the elements of an array. This function takes a sequence or array and then shuffle the places of the elements present in the given array.
Syntax
func shuffle()
Where this function does not take any parameter. Also it does not return any value instead it shuffle the places of the element in the given collection or array.
Example
In the following swift example, we will create and initialise an array of string type, then we shuffle the elements of the array using shuffle() function and display output.
import Foundation import Glibc // Creating an array var myfruites = ["Kiwi", "Orange", "Mango", "Apple", "Sweet Apple", "Papaya"] print("Original array:", myfruites) // Shuffle array elements myfruites.shuffle() print("Shuffled array:", myfruites)
Output
Original array: ["Kiwi", "Orange", "Mango", "Apple", "Sweet Apple", "Papaya"] Shuffled array: ["Mango", "Orange", "Kiwi", "Papaya", "Sweet Apple", "Apple"]
Conclusion
So this is how we can shuffle the elements of the array. Here shuffle() function shuffle the elements randomly, so whenever you run the code you will get different placement of elements in the output.
Advertisements