Grant Emerson

Indexing Into Randomness

Indexing 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: