我正在构建一个简单的应用程序,您可以单击按钮并随机更改图像,但是我还想添加描述图像的标签,因此我创建了包含["fileName":"Description"]
的字典,但是当我尝试更改时图片出现错误:
“无法为索引为'Int'的类型[[String:String]'下标”“
var randomNumber = 0
let arrayOfImages : [String:String] = ["ball1":"yes","ball2":"no","ball3":"ask again later","ball4":"the answer is yes","ball5":"i dont know"]
func rollButton() {
randomNumber = Int.random(in: 0...4)
ballImage.image = UIImage(named: arrayOfImages[randomNumber])
}
如何使用UIImage.image
来更改Dictionary
?
答案 0 :(得分:0)
您正在创建[String: String]
的列表,因此应使用键(字符串)而不是数字(整数)访问它。
所以您应该更正此问题:
ballImage.image = UIImage(named: arrayOfImages["ball\(randomNumber)"])
答案 1 :(得分:0)
替换
ballImage.image = UIImage(named: arrayOfImages[randomNumber])
使用
ballImage.image = UIImage(named: Array(arrayOfImages.keys)[randomNumber])
由于不能为数组添加字典下标,所以一个好习惯是创建
struct Item {
let imageName:String
let des:String
}
let arr = [Item(imageName: "ball1", des: "con1"),Item(imageName: "ball2", des: "con2"),Item(imageName: "ball3", des: "con3")]
let ran = arr[Int.random(in: 0...2)]
ballImage.image = ran.imageName