Getting random elements from a Swift array

by @ralfebert · updated November 02, 2021
Xcode 13 & iOS 15
Swift Examples

Use the randomElement method of the Swift Standard Library to get a random element from an array:

let names = ["Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Heidi"]

if let name = names.randomElement() {

There is no method to get multiple random elements, but you can get the job done using the shuffled method:


More information