1

could anyone teach me how to select an item (String) from an array by using arc4random_uniform()? I tried but I couldn't because arc4random_uniform can be used for selecting Int.

ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
Ryo Fukuda
  • 21
  • 1
  • 4

2 Answers2

3

Swift 3 Extension

While Oisdk answer works, a extension could be more useful instead of writing that coding over and over again.

import Foundation

extension Array {

  func randomElement() -> Element  {
     if isEmpty { return nil }
     return self[Int(arc4random_uniform(UInt32(self.count)))]
  }
}

let myArray = ["dog","cat","bird"]

myArray.randomElement() //dog 
myArray.randomElement() //dog 
myArray.randomElement() //cat 
myArray.randomElement() //bird
Alec O
  • 1,697
  • 1
  • 18
  • 31
2

Subscripting an array takes and Int, but arc4random_uniform returns a UInt32. So you just need to convert between those types.

import Foundation

let array = ["ab", "cd", "ef", "gh"]

let randomItem = array[Int(arc4random_uniform(UInt32(array.count)))]

Also, arc4random_uniform gives a random number less that its argument. So just cast array.count to a UInt32, and it'll work.

oisdk
  • 9,763
  • 4
  • 18
  • 36