To select a random element from an array in Swift, you can use the randomElement()
method that is available on arrays:
main.swift66 chars3 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.swift145 chars5 lines
This code would shuffle the array and then take the first three elements to retrieve three random elements from the array.
gistlibby LogSnag