Indexing Into Randomness
Published on Dec 20, 2019Indexing Into Randomness β SwiftMoji Entry #22
In most programming languages, to obtain a random element from an array one must first generate a random integer index value within a certain range. In Swift, this operation can be done in a more readable and convenient fashion using Arrayβs randomElement() method. The method returns an optional Element because it might return nil in the case that the array is empty.
import Foundation
let buffet = ["π", "π", "π", "π₯", "π―", "π₯"]
let dinner = buffet.randomElement()!
print("Tonight I will eat \(dinner).") // Tonight I will eat π.
Tagged with: