Swift .randomElement()
Anonymous contributor
Published Jul 8, 2023
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
Learn Swift on Codecademy
- Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
- Includes 7 Courses
- With Certificate
- Beginner Friendly.13 hours
- A powerful programming language developed by Apple for iOS, macOS, and more.
- Beginner Friendly.12 hours