Function “的结构;如果;及;否则";

Function “的结构;如果;及;否则";,function,swift,validation,if-statement,Function,Swift,Validation,If Statement,我是Swift的初学者,对“if”和“else”的结构有一个快速的问题。我正在学习关于验证用户名和密码的教程 这是我的当前代码: let username = "brian0306" let password = "secret" if (username == "brian0306") { println("If the username doesn't match then there's not much point checking whether password match

我是Swift的初学者,对“if”和“else”的结构有一个快速的问题。我正在学习关于验证用户名和密码的教程

这是我的当前代码:

let username = "brian0306"
let password = "secret"

if (username == "brian0306") {
    println("If the 
username
doesn't match then there's not much point checking whether
password
matches, so that's a perfectly good way to do it. You could shorten it to:

if username == "brian0306" && password == "secret" {
    println("❤️")
} else {
    println("Uh oh, your username or password is wrong!")
}
let username=“brian0306”
让password=“secret”
如果(用户名==“brian0306”){

println(“如果
用户名
不匹配,那么检查
密码
是否匹配就没有什么意义了,因此这是一个非常好的方法。您可以将其缩短为:


但是,这不会告诉您哪个字段不正确(
username
和/或
password
).

否,因为您首先检查用户名,如果用户名匹配,然后检查密码,因为您在其中有硬编码的值。您这样做是最好的方法。您仅针对1个用户进行验证,并且您知道用户名是否不匹配,因此没有必要检查密码。因此,您检查用户名,然后符合pas剑。@Josh Stevens没有什么真正的区别,就像你试图在第一次验证失败后立即验证用户名和密码,但第二次验证没有发生一样。什么?@IcaroNZ我在解释他是如何做到的,这很好,为什么网站会告诉他要编写代码way@bmoondesign这种方法的好处是你知道失败的是什么,用户名还是密码,但缺点是它会让你更难阅读code@JoshStevens对不起,我可能误解了你的意思。我只是指出,这两种方法之间没有计算上的好处,所以答案应该是,在这方面,它既不是更有效,也不是更有效