Author Topic: How do I get a random item from an array in Swift?  (Read 15113 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
How do I get a random item from an array in Swift?
« on: June 03, 2015, 09:16:12 AM »
To get a random item from an array, you simply need to generate a random index number and use that index to retrieve the item. For example:

Code: [Select]
let devices = ["Apple Watch", "iPhone", "iPad", "Mac", "Apple TV"]
// Generate a random index
let randomIndex = Int(arc4random_uniform(UInt32(devices.count)))
// Get a random item
let randomItem = devices[randomIndex]

All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11