Swift – Get Random Element from Set
To get random element from given Set in Swift, call randomElement() method on this Set. randomElement() returns an element that is picked randomly from this Set.
Examples
In the following example, we take set fruits, and get a random element from this set using Set.randomElement() method.
main.swift
</>
Copy
let fruits: Set = ["apple", "banana", "cherry", "mango"]
if let element = fruits.randomElement() {
print("Random Element : \(element)")
}
Output
Random Element : banana
Program ended with exit code: 0
If the set is empty, randomElement() returns nil
.
main.swift
</>
Copy
let fruits = Set<Int>()
let element = fruits.randomElement()
print("Random Element : \(element)")
Output
Random Element : nil
Program ended with exit code: 0
Conclusion
In this Swift Tutorial, we learned how to get a random element from given Set using Set.randomElement() method.