【问题标题】:Combine if statement and for loop such that loop only gets executed once per every execution of if statement in swift结合 if 语句和 for 循环,这样循环只会在 swift 中每次执行 if 语句时执行一次
【发布时间】:2020-07-17 01:58:08
【问题描述】:
我试图理解 swift,因此尝试想出简单的命令行游戏:在这个游戏中,玩家必须在 6 次尝试中通过在命令行中输入一些东西来猜测一个秘密单词,但每次他都得到它错误,一条语句打印出他的错误尝试次数:
let response = readLine()
if response != "secret word" {
for n in 1...6 {
print(n)
}
}
else {
print("you are right!")
}
现在我知道,一旦条件不成立,我的代码将打印所有行,但我正在寻找一种方法,为每个 if 语句连续打印四个循环中的一个项目。
【问题讨论】:
标签:
swift
for-loop
if-statement
command-line
【解决方案1】:
我认为 while 循环效果很好。也许是这样的:
print("Welcome to the input game!\n\n\n\n")
var remainingTries = 5
let dictionary = ["apple", "grape", "pear", "banana"]
let secretWord = dictionary.randomElement()
print("Please guess a fruit")
while remainingTries > 0 {
remainingTries -= 1
let response = readLine()
if response == secretWord {
print("You got it!")
remainingTries = 0
} else if remainingTries <= 0 {
print("Too bad, you lose!")
remainingTries = 0
} else {
print("Incorrect. Tries remaining: \(remainingTries)")
}
}