Open In App

How to shuffle the elements of a set in Swift?

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Swift program to shuffle all the element from the set
import Swift
  
// Creating a set of Authors rating
// Here the set is of float type
var AuthorRating: Set = [2, 458, 65, 8, 76, 4, 982, 3, 4, 5]
  
// Displaying original set
print("Original Set:", AuthorRating)
  
// Shuffle all the elements of the set
// Using shuffled() function
var result = AuthorRating.shuffled()
  
// Displaying the shuffled elements
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




// Swift program to shuffle all the element from the set
import Swift
  
// Creating a set of Author's name
// Here the set is of string type
var AuthorName: Set = ["Pihu", "Punit", "Sumit", "Rahul", "Mira"]
  
// Displaying original set
print("Original Set:", AuthorName)
  
// Shuffle all the elements of the set
// Using shuffled() function
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
Previous
Next
Share your thoughts in the comments
Similar Reads