问题
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:
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]
来源:https://stackoverflow.com/questions/33754957/pick-a-random-ui-image-view-swift-2