Swift: Arc4Random Type Casting

I’ve been struggling like usual with a relatively simple problem the last two days this time, it’s getting arc4random_uniform to give me a randomized value from an array. Sure, it’s an easy problem for someone more experienced, so prepare to laugh.

It occurred to me to type cast arc4random the instant I saw the error. I don’t know why it took me so long to actually figure out how to do it, but a helpful StackOverflow solution pointed me in the right direction:

let myFruits = ["bananas", "apples", "oranges", "grapes", "cherries"]
 let randomFruit = myFruits[Int(arc4random_uniform(UInt32(myFruits.count)))]
 println(randomFruit)

The thing with type casting arc4random (bear with me here), is because it takes a UInt32. Which is an unsigned 32-bit integer, this is a number that cannot dip into the negatives–unlike a regular integer which can dip into the negatives. I was trying to get it to spit out a regular integer and Swift was having none of that. Beyond what I got up there, I needed to output three values instead of just one, so I iterated through the randomization using a for loop to get my randomFruit values:

for var i = 0; i < 3; i++ {
let myFruits = ["bananas", "apples", "oranges", "grapes", "cherries"]
let randomFruit = myFruits[Int(arc4random_uniform(UInt32(myFruits.count)))]
println(randomFruit)
}

Up there is a standard for loop using a variable of i to interate 3 times. Each time the loop runs, it randomly chooses one of the values within the myFruits array and prints it out.

You should be able to get three randomized selections from the myFruits array at that point. Now, the values do get repeated, I haven’t worked out yet how to get it to select a unique fruit every time, but it’s a start. I don’t know if that code is great or ugly, all I know is that it works. If you have any suggestions for improvement, by all means let me know!

Resources

Randomly Select a Value Using Arc4Random_Uniform on StackOverflow


Posted

in

by