Reputation: 21
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.
Upvotes: 1
Views: 2802
Reputation: 31
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
Upvotes: 3
Reputation: 10091
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.
Upvotes: 2