Pick a random element from an array

arrays, random, swift

Solution

Swift 4.2 and above

The new recommended approach is a built-in method on the Collection protocol: `randomElement()`. It returns an optional to avoid the empty case I assumed against previously.

let array = ["Frodo", "Samwise", "Merry", "Pippin"]
print(array.randomElement()!) // Using ! knowing I have array.count > 0

If you don't create the array and aren't guaranteed count > 0, you should do something like:

if let randomElement = array.randomElement() { 
    print(randomElement)
}

Swift 4.1 and below

Just to answer your question, you can do this to achieve random array selection:

let array = ["Frodo", "Samwise", "Merry", "Pippin"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])

The castings are ugly, but I believe they're required unless someone else has another way.

Problem

Suppose I have an array and I want to pick one element at random. What would be the simplest way to do this? The obvious way would be `array[random index]`. But perhaps there is something like ruby's `array.sample`? Or if not could such a method be created by using an extension?

Original source

Related problems