Swift – Get Random Element from Array

To get a random element from an array in Swift, call randomElement() method on this Array.

Array.randomElement() returns an element that is randomly picked from the elements of this array. If the array is empty, then this method returns nil.


The syntax to call access last element of Array array is


We may use this property with if statement as shown in the following.

if let x = array.randomElement() {
    print("Random Element : \(x)")


In the following program, we take an array of size five, and get a random element from this array using Array.randomElement().


var nums = [2, 4, 6, 8, 10]
if let x = nums.randomElement() {
    print("Random Element : \(x)")


Random Element : 2
Program ended with exit code: 0


In this Swift Tutorial, we learned how to get a random element from an Array in Swift programming.