To get a random element from an array you can use the randomElement()
function for arrays.
Here is a code example:
let numbers = [5, 2, 9, 11, 20, 3030]
if let random = numbers.randomElement() {
print("The random number is \(random).")
}
The reason we need the if let
is because randomElement()
returns an optional. It will return nil if your array is empty.
Here’s an example where it will return nil
:
let emptyArray: [Int] = []
print(emptyArray.randomElement()) // nil
This also works with any type of array, here’s an example of a String
array:
let names = "Eddy, Edson, Chika, Manju, Hamilton, Amber, Disha, Soumya, Rohit"
if let random = names.randomElement() {
print("The random name is \(random).")
}
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.