Swift, how to get a random item from an array
This tutorial belongs to the Swift series
Suppose you have an array in Swift, like this:
let items = [1, 2, 3]
and you want to get a random number out of it.
The Array data type provides the randomElement()
function that returns an Element?
:
let item = items.randomElement()
→ Here's my latest YouTube video
→ Get my Swift Handbook
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025