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.
Asked
Active
Viewed 2,767 times
1

ABakerSmith
- 22,759
- 9
- 68
- 78

Ryo Fukuda
- 21
- 1
- 4
-
3Have a look at http://stackoverflow.com/questions/24003191/pick-a-random-element-from-an-array – ABakerSmith May 17 '15 at 16:48
-
Basically as shown in the question above, you just have to declare the random number as a Integer like so `Int(randomNumber)` That makes the type of your number an integer instead of a UInt32 – Brennan Adler May 17 '15 at 18:22
-
i mean how can i chage String form into Integer? – Ryo Fukuda May 18 '15 at 01:51
2 Answers
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

James Ikeler
- 31
- 2
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