In Swift, we can get a random element from an array by using randomELement()
. If the array is empty, nil
is returned.
arr.randomElement()
This method does not take any parameters.
This method returns an element from the array arr
, picked at random.
// create arrays let numbers = [1, 3, 10, 4] let techCoys = ["Google", "Amazon", "Netflix"] // get random elements let randomNum = numbers.randomElement()! let randomTechName = techCoys.randomElement()! // print random elements print(randomNum) print(randomTechName)
In the above code snippet:
numbers
and techCoys
.randomElement()
method on the arrays we created, and store the elements inside variables randomNum
and randomTechName
.RELATED TAGS
CONTRIBUTOR
View all Courses