.randomElement()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Jul 8, 2023
Contribute to Docs

The .randomElement() method will return a random element from an array or another given collection.

Syntax

arrayName.randomElement()

The method selects a random element from the collection arrayName. If the passed collection is empty, it will return nil.

Example

A basic implementation of the .randomElement() method:

var discount = ["10%", "20%", "30%", "40%", "50%"]
let randomDiscount = discount.randomElement()!
let randomDiscount2 = discount.randomElement()!
print(randomDiscount)
print(randomDiscount2)

The output will be similar to:

10%
50%

All contributors

Looking to contribute?

Learn Swift on Codecademy