Pick Random Element From Array In Swift

By Eddy Chung

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).")
}
If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts