Pick a random UI Image View - Swift 2

2019-09-13 20:29发布

So I have 3 images

 @IBOutlet weak var imageOne: UIImageView!
  @IBOutlet weak var imageThree: UIImageView!
  @IBOutlet weak var imageTwo: UIImageView!

I generate a random image from an array of images, the random image generated is the "correct" image

Here is how I was currently doing it

  let randomIndex = Int(arc4random_uniform(UInt32(famousPeople.count)))
  let correct = famousPeople[randomIndex]
  self.imageOne.image = UIImage(named: correct)

Obviously the issue with this is the imageOne is always the correct image, I want the correct image to be random either one two or three.

I thought I could do the following

let randomImageIndex = Int(arc4random_uniform(UInt32(famousPeople.count)))
            var imageArray: [String] = ["imageOne", "imageTwo", "imageThree"]
            let randomImage = imageArray[randomImageIndex]

then

self.randomImage.image = UIImage(named: correct)

However I get the error message view controller no type random image.

Is there a good way to choose a random UI imageview? and then I want to assign to it my randomly chosen "correct" image

Extra context

The user can then choose the "correct" image and gets a message

1条回答
家丑人穷心不美
2楼-- · 2019-09-13 20:38
import Foundation

var number1 = 0
var number2 = 0
var number3 = 0

// You would like randomly choose one of number1, number2 and number2
// and assign to it random number ...

func foo(inout n: [Int]) {
    let i = Int(arc4random_uniform(UInt32(n.count)))
    for j in 0..<n.count {
        if i == j {
            n[j] = random()
        } else {
            n[j] = 0
        }
    }
}

var arr = [number1, number2, number3]
foo(&arr) // [0, 1804289383, 0]
foo(&arr) // [846930886, 0, 0]
foo(&arr) //  [0, 0, 1681692777]
查看更多
登录 后发表回答