简体   繁体   中英

how to initiate a variable in a UIImage(named: firstImage = array.sample()) in swift

I just started with Swift programming. I'm trying to display a random image to the UIImageView randomly. sample() is my random function. so I declare the variable as such:

var firstImage: String

then i use:

prototypeImage1.image = UIImage(named: firstImage = array.sample())

so I can use the variable firstImage in another method so I can display the picture clicked on to another spot. but it keeps giving me a compiler around saying that "() is not convertible to String"

Edit:

func setImageForSpot(){ 
    prototypeImage1.image = UIImage(named: firstImage = array.sample()) 
    prototypeImage2.image = UIImage(named: secondImage = array.sample()) 
    prototypeImage3.image = UIImage(named: thirdImage = array.sample())
}
func chooseSpotToDisplayWhenClicked(spot:Int){
    switch spot {
        case 0: prototypeImage6.image = UIImage(named: firstImage)
        case 1: prototypeImage6.image = UIImage(named: secondImage)
        case 2: prototypeImage6.image = UIImage(named: thirdImage)
        default: prototypeImage6.image = nil 
    }
 }

You can't assign a value to firstImage like this. Just break it down and it should work if your sample() function is working correctly. BTW Swift is a type-inferred language. Give it a try.

extension Array {
    var sample:T {
    return self[ Int(arc4random_uniform(UInt32(count))) ]
    }
}
let inputArray = ["named1", "named2"]
var firstImage = ""

firstImage = inputArray.sample // "named1"
prototypeImage1.image = UIImage(named: firstImage)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM