Swift – Get Shuffled Elements of a Set

To get shuffled elements of a Set in Swift, call shuffled() method on this Set. shuffled() returns shuffled elements of Set as an Array.

Examples

In the following example, we take a Set nums and shuffle the elements using shuffled() method.

main.swift

</>
Copy
let nums: Set = [2, 4, 6, 18, 10]
let result = nums.shuffled()
print("Original : \(nums)")
print("Shuffled : \(result)")

Output

Original : [10, 4, 2, 18, 6]
Shuffled : [6, 4, 2, 10, 18]
Program ended with exit code: 0
Original : [6, 10, 2, 4, 18]
Shuffled : [18, 6, 2, 10, 4]
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to shuffle elements of a Set using Set.shuffled() method.