Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick a random element from an array

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?

like image 879
Fela Avatar asked Oct 20 '22 11:10

Fela


2 Answers

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.

like image 352
Lucas Derraugh Avatar answered Oct 22 '22 00:10

Lucas Derraugh


Riffing on what Lucas said, you could create an extension to the Array class like this:

extension Array {
    func randomItem() -> Element? {
        if isEmpty { return nil }
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

For example:

let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16]
let myItem = myArray.randomItem() // Note: myItem is an Optional<Int>
like image 138
Phae Deepsky Avatar answered Oct 22 '22 01:10

Phae Deepsky