斯威夫特:"哪里"与"如果"

ger*_*bil 1 if-statement where swift

这两种语法之间有什么区别吗?如果没有,有什么好处?

if let userName = userNameTextField.text where userName.characters.count > 0,
        let password = passwordTextField.text where password.characters.count > 0,
        let confirmation = confirmationTextField.text where confirmation == password
    else {
        return false
    }
Run Code Online (Sandbox Code Playgroud)

和:

if userNameTextField.text?.characters.count > 0 &&
        passwordTextField.text?.characters.count > 0 &&
    confirmationTextField.text == passwordTextField.text
    {
        return false
    }
Run Code Online (Sandbox Code Playgroud)

dfr*_*fri 6

首先,请注意,whereSwift 3.0中不推荐使用可选绑定条件中的子句,替换为,.

let opt: Int?

/* Swift < 3 */
if let opt = opt where opt == 42 { /* ... */ }

/* Swift >= 3 */
if let opt = opt, opt == 42 { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

其次,你的第二个示例块不会在Swift> = 3.0中编译,因为可选链接的可选结果未解包; 根据以下实施的提议,在Swift 3.0中删除了将选项与文字进行比较(感谢@MartinR):

userNameTextField.text?.characters.count > 0 &&
/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   this is an optional that, for Swift >= 3.0, needs to be unwrapped 
   prior to comparing it to the integer literal */
Run Code Online (Sandbox Code Playgroud)

现在,继续回答你的"有什么不同......"的问题,假设我们看看你为Swift 3修复的两个选项.

  • 您可以选择可选的值绑定String属性textuserNameTextField ,如果你想在后面的if块使用它,或
  • 如果您只想确定该text属性不是nil或为空(""),您可以省略有利的绑定或只是检查它character.count

例如:

struct Foo {
    var bar: String?
}
var foo = Foo()

/* if you want to use foo.bar within the if block */
if let str = foo.bar, str.characters.count > 0 {
    // do something with str ...
    print(str)
}

/* if you only need to ascertain foo.bar is not nil
   and not empty */
if (foo.bar?.characters.count ?? 0) > 0 {
    // do something with str ...
    print("not empty")
}

// alternatively ... (not nil or empty)
if !(foo.bar?.isEmpty ?? true) {
    // do something with str ...
    print("not empty")
}
Run Code Online (Sandbox Code Playgroud)

如果您只是想确定后者并false在确定失败的情况下返回,您可能更喜欢使用guard语句而不是if:

guard (foo.bar?.characters.count ?? 0) > 0 else { return false }
// ... if no false return, proceed with app flow here ...

// alternatively ...
guard !(foo.bar?.isEmpty ?? true) else { return false }
Run Code Online (Sandbox Code Playgroud)