我正在使用一个 if 语句,它应该会打破循环。有人能帮我吗? (Swift 游乐场)

I'm using an if statement, which is supposed to break the loop. Can Someone help me? (Swift Playgrounds)

//循环没有中断。这很奇怪。我试图修复它,但没有用。我在 python 中尝试了相同的代码。同样的事情发生了。

let code = "QQQQQQQQ"
let characters = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890!@#$%^&*()-=+_"
var cracker = ""

for letter in characters {
    for letter2 in characters{
        for letter3 in characters {
            for letter4 in characters {
                for letter5 in characters {
                    for letter6 in characters {
                        for letter7 in characters {
                            for letter8 in characters {
                                cracker = "\(letter)\(letter2)\(letter3)\(letter4)\(letter5)\(letter6)\(letter7)\(letter8)"
                                print(cracker)
                                if cracker == code {
                                    break
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

一次休息只会让你跳出一个循环,而不是所有循环。不要这样做,你应该做的是为整个循环创建另一个函数。在 python->

def check(characters):
    for letter in characters :
        for letter2 in characters:
            for letter3 in characters :
                for letter4 in characters :
                    for letter5 in characters :
                        for letter6 in characters :
                            for letter7 in characters :
                                for letter8 in characters :
                                    cracker = "\(letter)\(letter2)\(letter3)\(letter4)\(letter5)\(letter6)\(letter7)\(letter8)"
                                    print(cracker)
                                    if cracker == code:
                                        print("Found")
                                        return;
    print("Not Found!")
    return

因此,当您找到答案时,打印类似“FOUND”和 return 的内容,这样您就知道您找到了答案,如果您没有找到答案,则在所有循环结束时打印一些内容像“未找到”和 return.