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.
2 Answers
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
Comments
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.
1 Comment
Alec O
This will crash if there are no items.
Int(randomNumber)That makes the type of your number an integer instead of a UInt32