How to shuffle the elements of a set in Swift?
A set is an unordered generic collection that is used to store elements of the same type. It means you are not allowed to keep different types in the set. You can use a set instead of an array if the order of the values is not defined or you want to store unique values. It doesn’t keep duplicate values, it always keeps unique values in it. It generally uses a hash table to store the elements. A set can be mutable or immutable. If a set is assigned to a variable then that set is known as a mutable set. Or if a set is assigned to a constant then that set is known as an immutable set. In Set, we can easily shuffle the elements using the shuffled() function. This function is used to shuffle all the elements from the specified set. It does not take any parameters.
Syntax:
setName.shuffled()
Here,
setName is the object of the set class.
Return Value: It will return the shuffled elements of the specified set.
Example 1:
Swift
import Swift
var AuthorRating: Set = [2, 458, 65, 8, 76, 4, 982, 3, 4, 5]
print ( "Original Set:" , AuthorRating)
var result = AuthorRating.shuffled()
print ( "Shuffled elements:" , result)
|
Output:
Original Set: [458, 76, 982, 8, 5, 4, 3, 65, 2]
Shuffled elements: [65, 5, 4, 982, 76, 8, 2, 3, 458]
Example 2:
Swift
import Swift
var AuthorName: Set = [ "Pihu" , "Punit" , "Sumit" , "Rahul" , "Mira" ]
print ( "Original Set:" , AuthorName)
print ( "Final Set:" , AuthorName.shuffled())
|
Output:
Original Set: ["Rahul", "Mira", "Sumit", "Pihu", "Punit"]
Final Set: ["Sumit", "Rahul", "Pihu", "Punit", "Mira"]
Last Updated :
02 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...