ralph007
ralph007

Reputation: 67

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 
    }
 }

Upvotes: 1

Views: 704

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236558

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)

Upvotes: 1

Related Questions