如果语句没有执行。更改为开关时,仅执行默认情况

问题描述 投票:-1回答:1

我正在创建一个刽子手应用程序,当我删除代码时,if语句不起作用,但仅适用于一个动物。代码应更新标签,如果单词包含该字母,则将您按下的字母放在适当的位置。我试过创建一个开关

(随机是从一系列动物中选择的单词)

switch random {
case "aardvark":
(the code for when random is aardvark)
default:
(the code for sea turtle) }

但默认情况下每次都会执行,即使随机是aardvark

@IBAction func aPressed(_ sender: Any) {

    if random == "aardvark" {
    if aardvark[0] == "a" {
        aar[0] = "a"
    };if aardvark[1] == "a" {
        aar[1] = "a"
    };if aardvark[2] == "a" {
        aar[2] = "a"
    };if aardvark[3] == "a" {
        aar[3] = "a"
    };if aardvark[4] == "a" {
        aar[4] = "a"
    };if aardvark[5] == "a" {
        aar[5] = "a"
    };if aardvark[6] == "a" {
        aar[6] = "a"
    };if aardvark[7] == "a" {
        aar[7] = "a"
    } else if aardvark[0] != "a" , aardvark[1] != "a" , aardvark[2] != "a" , aardvark[3] != "a" , aardvark[4] != "a" , aardvark[5] != "a" , aardvark[6] != "a" , aardvark[7] != "a" {
        wrong += 1
    }
        theWord.text = self.aar.joined(separator: " ")
    }

    if random == "sea turtle" {
   if seaTurtle[2] == "a" {
        sTurt[2] = "a"
        theWord.text = self.sTurt.joined(separator: " ")
   }
    }
    buttonA.isHidden = true
    updateImage()
    }
swift if-statement switch-statement
1个回答
1
投票

除了你的代码所带来的结构性问题之外,你还要考虑到你不能只是对每个字母的检查进行硬编码,一个接一个。您的代码需要循环(通过您编写的循环显式地循环,或通过使用循环的函数隐式地)通过答案的字母循环,将它们与猜测进行比较,并适当地修改游戏板。这是一个例子:

let word = "Aardvark"
var gameBoard = "XXXXXXXX"
let guess: Character = "a"

let indicies = zip(word.lowercased(), word.indices).flatMap{ (pair: (letter: Character, index: String.Index)) in
    return pair.letter == guess ? pair.index : nil
}

indicies.forEach{ gameBoard.replaceSubrange($0...$0, with: word[$0...$0]) }

print(gameBoard) //AaXXXaXX
© www.soinside.com 2019 - 2024. All rights reserved.