select a random element from an array in swift

To select a random element from an array in Swift, you can use the randomElement() method that is available on arrays:

main.swift
let arr = [1, 2, 3, 4, 5]
let randomElement = arr.randomElement()
66 chars
3 lines

This will return an optional value that will be either the randomly selected element from the array or nil if the array is empty.

If you want to select multiple random elements from an array, you could use the shuffled() method to shuffle the array and then take a slice of the desired length:

main.swift
let arr = [1, 2, 3, 4, 5]
let numRandomElements = 3
let shuffled = arr.shuffled()
let randomElements = Array(shuffled.prefix(numRandomElements))
145 chars
5 lines

This code would shuffle the array and then take the first three elements to retrieve three random elements from the array.

gistlibby LogSnag