如果语句没有执行。更改为开关时,仅执行默认情况
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果语句没有执行。更改为开关时,仅执行默认情况相关的知识,希望对你有一定的参考价值。
我正在创建一个刽子手应用程序,当我删除代码时,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()
}
答案
除了你的代码所带来的结构性问题之外,你还要考虑到你不能只是对每个字母的检查进行硬编码,一个接一个。您的代码需要循环(通过您编写的循环显式地循环,或通过使用循环的函数隐式地)通过答案的字母循环,将它们与猜测进行比较,并适当地修改游戏板。这是一个例子:
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
以上是关于如果语句没有执行。更改为开关时,仅执行默认情况的主要内容,如果未能解决你的问题,请参考以下文章
为啥如果我更改为 INPUT_GET 此代码将始终执行“其他”代码