为什么带有两个操作数的语句需要高于具有一个操作数的语句才能正确输出?

时间:2015-10-29 23:31:51

标签: swift

当我创建不正确的属性并放入

else if username != "tigerclaw" && password != "888love" {
print("Re-enter username and password")
}
在我的块底部的

当输入不正确时,Xcode不会打印出“重新输入用户名和密码”。

是因为具有相同数量的操作数的语句需要一个接一个吗?因为这有用。

let username: String = "2igerclaw"
let password: String = "x88love"

if username == "tigerclaw" && password == "888love" {
print("Acess Granted")

} else if username != "tigerclaw" && password != "888love" {
print("Re-enter username and password")


} else if username != "tigerclaw" {
print("Re-enter username")

} else if password != "888love" {
print("Re-enter password")

}

1 个答案:

答案 0 :(得分:2)

您正在使用else if来连接所有这些语句。当您使用else语法时,仅在先前条件未评估为true时才会检查条件。例如:

if (true) {
  // This code will execute because true is, well true.
} else (true) {
  // This code WILL NOT execute, because the else statement will never be checked because we fell inside the first conditional.
}

如果您想同时执行这两个,那么您需要将语句分开。例如:

if (true) {
  // This will be excuted because true is, well true.
}

if (true == true) {
    // This will also be executed because true is still true and we are not limiting it by the else.
}