MK4 MK4 - 1 year ago 70
Swift Question

select random image from two different arrays

I need to send an image to UIImageView randomly from two different arrays. I am not sure how do i proceed with this?

var imgSetOne: [String] = ["car1.png", "car2.png", "car3.png", "car4.png", "car5.png"]
let imgOneRandom = Int(arc4random_uniform(5))

var imgSetTwo: [String] = ["bus1.png", "bus2.png", "bus3.png", "bus4.png", "bus5.png"]
let imgTwoRandom = Int(arc4random_uniform(5))

UIImage(named: imgSetOne[imgOneRandom]) OR UIImage(named: imgSetTwo[imgTwoRandom])

I am trying to select random image from first array and second array using arc4random_uniform. Now i want to display image either from first array result or second array result to the UIImageView.

Answer Source

If your arrays have the same size, then you can just select array to pick image randomly:

let arrayIndex = Int(arc4random_uniform(2))
UIImage(named: arrayIndex == 0 ? imgSetOne[imgOneRandom] : imgSetTwo[imgTwoRandom])

Note that if arrays have different size and you still want to choose each image from both arrays with same probability you will need to tweak this logic a little (will leave it as a homework excersize)