如何为(太大)IF 语句重写代码?
How to rewrite code for a (too) big IF statement?
我有一个项目,其中显示了一些 UIbuttons
,其中显示了不同的 UIimages
。通过用户交互,UIButtons
中可能存在任何UIimages
。项目中大约有 1000 张图像。我已经初始化了一个名为 'i' 的变量。在所有按钮上还有一个名为 buttonTapped 的 IBAction
。现在我想更新变量 'i' 并为每个不同的可能的“UIImage”使用 'i' 的值。我可以使用 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
但我想要一个比 IF 语句更好的解决方案,它包含大约 1000 个 else if(s)。我已经尝试过,但我无法简明扼要地重写代码。我可以使用什么来代替 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( { [=12=].image == sender.currentImage } )
if let match = matches.first {
// use match.index
}
}
我有一个项目,其中显示了一些 UIbuttons
,其中显示了不同的 UIimages
。通过用户交互,UIButtons
中可能存在任何UIimages
。项目中大约有 1000 张图像。我已经初始化了一个名为 'i' 的变量。在所有按钮上还有一个名为 buttonTapped 的 IBAction
。现在我想更新变量 'i' 并为每个不同的可能的“UIImage”使用 'i' 的值。我可以使用 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
但我想要一个比 IF 语句更好的解决方案,它包含大约 1000 个 else if(s)。我已经尝试过,但我无法简明扼要地重写代码。我可以使用什么来代替 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( { [=12=].image == sender.currentImage } )
if let match = matches.first {
// use match.index
}
}