Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
swift
random
communitycreator

How to get a random element from an array in Swift

Theodore Kelechukwu Onyejiaku

Overview

In Swift, we can get a random element from an array by using randomELement(). If the array is empty, nil is returned.

Syntax

arr.randomElement()

Parameters

This method does not take any parameters.

Return value

This method returns an element from the array arr, picked at random.

Example

// 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)
Get random elements from arrays in Swift

Explanation

In the above code snippet:

  • Line 2 and 3: We create arrays numbers and techCoys.
  • Line 5 and 6: We call the randomElement() method on the arrays we created, and store the elements inside variables randomNum and randomTechName.
  • Line 8 and 9: We print the results.

RELATED TAGS

array
swift
random
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring