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
.
Syntax
The syntax to call access last element of Array array
is
array.randomElement()
We may use this property with if statement as shown in the following.
if let x = array.randomElement() { print("Random Element : \(x)") }
ADVERTISEMENT
Examples
In the following program, we take an array of size five, and get a random element from this array using Array.randomElement().
main.swift
var nums = [2, 4, 6, 8, 10] if let x = nums.randomElement() { print("Random Element : \(x)") }
Output
Random Element : 2 Program ended with exit code: 0
Conclusion
In this Swift Tutorial, we learned how to get a random element from an Array in Swift programming.