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() {
    print(name)
}

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

print(names.shuffled().prefix(3))

More information