简体   繁体   English

如何在一个UIImage(名为:firstImage = array.sample())中快速初始化一个变量

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

I just started with Swift programming. 我刚开始使用Swift编程。 I'm trying to display a random image to the UIImageView randomly. 我正在尝试向UIImageView随机显示随机图像。 sample() is my random function. sample()是我的随机函数。 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. 因此我可以在另一种方法中使用变量firstImage,以便显示单击到其他位置的图片。 but it keeps giving me a compiler around saying that "() is not convertible to String" 但是它总是给我一个编译器,说“()不能转换为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. 您不能像这样为firstImage分配值。 Just break it down and it should work if your sample() function is working correctly. 只需分解一下,如果您的sample()函数正确运行,它就可以工作。 BTW Swift is a type-inferred language. BTW Swift是一种类型推断语言。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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