我有一个项目,其中有一些UIbuttons
,其中显示了不同的UIimages
。通过用户交互,UIButtons
中可能存在任何 UIimages
。该项目中有大约 1000 张图像。我已经初始化了一个名为“i”的变量。还有一个名为“buttonTapped”的 IBAction
在所有按钮上。现在我想更新变量“i”并将“i”的值用于每个不同的可能的“UIImage”。我可以使用 IF 语句来完成此操作,如下所示:
@IBAction func buttonTapped(sender: UIButton) {
if sender.currentImage == UIImage(named: "image1") {
i = 1
print(i)
// use the value of i
} else if sender.currentImage == UIImage(named: "image2") {
i = 2
print(i)
// use the value of i
} else if sender.currentImage == UIImage(named: "image3") {
i = 3
print(i)
// use the value of i
} else if // and so on
但我想要一个比包含大约 1000 个 else if 的 IF 语句更好的解决方案。我已经尝试过,但我无法简洁地重写代码。我可以用什么来代替 IF 语句?某种循环?
最佳答案
粗略的解决方案(假设索引都是连续的)
for i in 1 ... 1000 { // or whatever the total is
if sender.currentImage == UIImage(named: "image\(i)") {
print(i)
// use i
}
}
更好的解决方案,特别是如果名称不是您给出的格式时,是拥有一个结构数组(或者只是一个图像数组,如果数字都是连续的)...
struct ImageStruct {
var image: UIImage
var index: Int
}
var imageStructs:[ImageStruct]... // Some code to fill these
...
@IBAction func buttonTapped(sender: UIButton) {
let matches = self.imageStructs.filter( { $0.image == sender.currentImage } )
if let match = matches.first {
// use match.index
}
}
关于swift - 如何重写(太大)IF 语句的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33421059/