【问题标题】:How to rewrite code for a (too) big IF statement?如何为(太大)的 IF 语句重写代码?
【发布时间】:2015-10-29 17:37:37
【问题描述】:

我有一个项目,其中显示了一些 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

但我想要一个更好的解决方案,然后是一个包含大约 1000 个 else if(s) 的 IF 语句。我已经尝试过,但我无法简洁地重写代码。我可以用什么来代替 IF 语句?某种循环?

【问题讨论】:

    标签: swift loops if-statement uibutton uiimage


    【解决方案1】:

    一个粗略的解决方案(假设索引都是连续的)是

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

    【讨论】:

    • 谢谢,粗略的解决方案对我有用。更好的解决方案;我稍后会实施该解决方案。
    • ...每次用户按下按钮时,它将从您的资源中加载(最多)1000 张图像!考虑至少将所有图像预加载到一个数组中......
    • 是的,感谢您的建议。我一定会这样做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-03
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多