How to pick a random element from an array in Swift

Swift Standard Library provides a randomElement() method to return a random element from an array or nil if the array is empty.

If you know that your array is not empty, then go ahead and force unwrap the result of randomElement() method:

let array = ["Swift", "SwiftUI", "UIKit", "Foundation”]
let randomElement = array.randomElement()!

print(randomElement)

However, if you can’t make any assumptions about the input array, use the if let statement to test for possible nil value:

let array = ["Swift", "SwiftUI", "UIKit", "Foundation”]

if let randomElement = array.randomElement() {
    print(randomElement)
}

Or use the guard statement to check if the input array is empty and return early:

let array = ["Swift", "SwiftUI", "UIKit", "Foundation”]

guard array.count > 0 else {
    return
}

let randomElement = array.randomElement()!
print(randomElement)

Note that the randomElement() method uses a default random number generator provided by the system.

Related Swift tips and tutorials:

Check out Apple’s official documentation of the randomElement() method.