如何在swift ios中以最佳方式执行多个if语句

时间:2017-12-05 13:49:11

标签: ios swift if-statement

我已经定义了一个执行多个if语句的函数。虽然它只执行if语句但不执行定义它的流中的else语句。在相应的if语句的相应调用之后,我必须做什么才能执行else语句。

  func levelTwo() {

    if firstText.text == "A"
    {
        hintLabel.text = "\(self.hintsTwo[1])"
        self.firstValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.firstValid.image = #imageLiteral(resourceName: "markQ")
    }

    if SecFirstText.text == "A" && secSecText.text == "C"
    {
        hintLabel.text = "\(self.hintsTwo[2])"
        self.secondValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.secondValid.image = #imageLiteral(resourceName: "markQ")
    }

    if thiFirstText.text == "C" && thiSecText.text == "A" && thiThirdText.text == "T"
    {
        hintLabel.text = "\(self.hintsTwo[3])"
        self.thirdValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.thirdValid.image = #imageLiteral(resourceName: "markQ")
    }

}

2 个答案:

答案 0 :(得分:6)

您可以使用tuples开关:

switch(firstText.text, thiSecText.text) {
    case ("A", _):
        //First text equal a, second text equal anything
        break
    case ("A", "C"):
        //First text A, second text B
        break
    case (_, "B"):
        //First text anything, second text B
        break
    default:
        break
}

答案 1 :(得分:0)

你也可以使用这种结构(简化,但核心思想是可见的):

class MyClass {
    var firstText = "One"
    var secondText = "Two"
    var thirdText = "Three"
    var firstImage: UIImage?
    var secondImage: UIImage?
    var thirdImage: UIImage?
}

let instance = MyClass()

let keyPaths = [\MyClass.firstText:\MyClass.firstImage,
                \MyClass.secondText:\MyClass.secondImage,
                \MyClass.thirdText:\MyClass.thirdImage]

for (text, image) in keyPaths {
    if instance[keyPath: text] == "Two" {
        instance[keyPath: image] = UIImage()
    }
}