Swift多重IF语句

时间:2016-01-06 21:31:36

标签: swift

我正试图在测验中有3个生命特征。

所以我添加了三个按钮:

btnLife1
btnLife2
btnLife3

我的前两个条件完美无缺,前两个生命在测验中消失了。但是,当涉及到隐藏btnLife3时,它并没有隐藏在序列中 - 我想不出为什么,我的语法错了还是什么?

以下是我正在使用的代码:

//three lives start

            // if life 1 is visible
            // make life 1 hidden
            if (btnLife1?.hidden == false) {
                btnLife1!.hidden = true
            }
            // if life 1 is hidden
            // make life 2 hidden
            else if (btnLife1?.hidden == true) {
                btnLife2!.hidden = true
            }
            // if life 2 is hidden
            // make life 3 hidden
            else if (btnLife2?.hidden == true){
                btnLife3!.hidden = true
            }
            else if (btnLife3?.hidden == true) {
                //Game over
                DBFunction.insertData(self.playerName, score:String(format: "%d",self.playerScore))
                //{
                let scoreViewController = self.storyboard?.instantiateViewControllerWithIdentifier("scoreVC") as! ScoreviewController
                scoreViewController.playerScore = self.playerScore
                self.navigationController?.pushViewController(scoreViewController, animated: true)
            }

            else {
                //
            }
            //three lives end

2 个答案:

答案 0 :(得分:2)

是的,逻辑上存在缺陷。

将您的第二个条件更改为:

        // if life 1 is hidden AND life 2 is NOT hidden
        // make life 2 hidden
        else if (btnLife1?.hidden == true && btnLife2?.hidden == false) {
            btnLife2!.hidden = true
        }

加成:

您的变量必须是选项吗?你可以用这种方式简化它:

let lives : [UIButton] = [btnLife1, btnLife2, btnLife3]

for life in lives {

    if !life.hidden {

        life.hidden = true
        return
    }
}
// Game Over if the control came through the for-loop without returning.

答案 1 :(得分:1)

第二个条件不能被锁定。你需要一个新的条件,试试这个:

 // if life 1 is hidden AND life 2 is NOT hidden
 // make life 2 hidden
 else if (btnLife1?.hidden == true) && (btnLife2?.hidden == false) {
   btnLife2?.hidden = true
 }