.randomElement()
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 contributor
Contribute to Docs
- 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.
Learn Swift on Codecademy
- Skill path
Build iOS Apps with SwiftUI
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.Includes 7 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn Swift
A powerful programming language developed by Apple for iOS, macOS, and more.Beginner Friendly12 hours