Using Arc4random to get random image from list

162 Views Asked by At

I created a list called imageNames. and i used thise chunk of code to get a random image

@IBAction func showImages(_ sender: Any) {

    let RandomImage: Int = Int
        (arc4random_uniform(20))
    imageOne.image = UIImage (named:
        imageNames[RandomImage])

for some reason it won't work for me. i thought about making a var instead og let but still it gives me an error at int = int

anyone care to assist?

5

There are 5 best solutions below

0
Shehata Gamal On

I think you need it one line

let RandomImage = Int(arc4random_uniform(20))

Also look here for Swift 4.2 random number generation

2
Duncan C On

Get rid of the newline between Int and the (. That's what's causing your error.

Also, you should use the size of the array of images names to control the range of your random index. (If you hard-code the range of numbers and then later change your array of image names you'll either crash if your have less names in the array, or silently never select any of the new names if you don't increase the max index.)

And while we're at it, variable names should start with a lower-case letter. Consider this code:

@IBAction func showImages(_ sender: Any) {
    //Sample image names - replace with your own array of names
    let imageNames = ["one", "two", "three"]

    let randomIndex: Int = Int(arc4random_uniform(UInt32(imageNames.count)))
    let randomName = imageNames[randomIndex]
    imageOne.image = UIImage(name: randomName)
}
4
Chris On

Here’s an answer for Swift 4.2, where arc4random is not necessary.

@IBAction func showImages(_ sender: Any) {
    let randomIndex = Int.random(in: 0..<imageNames.count)
    imageOne.image = UIImage(named: imageNames[randomIndex])
0
Hendra Kusumah On

I prefer to use shuffle() method to reorder an array elements randomly.

0
vadian On

In Swift 4.2 it's still easier

imageOne.image = UIImage(named: imageNames.randomElement())