.randomElement()
Anonymous contributor
Anonymous contributor1 total contribution
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
- Anonymous contributorAnonymous contributor1 total contribution
- Anonymous contributor
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.