guard let error: Initializer for conditional binding must have Optional type not 'String'

guard let error: Initializer for conditional binding must have Optional type not 'String'

我在使用 guard let 时遇到致命错误。这是错误:

Initializer for conditional binding must have Optional type not 'String'

下面是我使用过的代码:

@IBAction func signUpButtonPressed(sender: UIButton) {
    guard let email = emailTextField.text! where emailTextField.text!.characters.count > 0 else {
        // alert
        return
    }

    guard let password = passwordTextField.text! where passwordTextField.text!.characters.count > 0 else {
    // alert
       return
   }

     self.registerUserAsync(email, password: password)
}

你应该非常小心选择。使用 ! 告诉 Swift 编译器您可以保证该值存在。 尝试这样做:

@IBAction func signUpButtonPressed(sender: UIButton) {
    guard let email = emailTextField.text where email.characters.count > 0 else {
        // alert
        return
    }

    guard let password = passwordTextField.text where password.characters.count > 0 else {
        // alert
        return
    }

    self.registerUserAsync(email, password: password)

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”.

您可以在此处找到有关可选选项的更多信息https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309

你正在解开可选的是什么使绑定变得毫无意义并导致错误:

emailTextField.text! // see the exclamation mark

错误信息说条件绑定必须是可选的(text 属性默认是可选的),所以删除感叹号:

emailTextField.text

一种更简单的语法是 isEmpty,您可以将代码减少到一个 guard 语句。

@IBAction func signUpButtonPressed(sender: UIButton) {
     guard let email = emailTextField.text where !email.isEmpty,
           let password = passwordTextField.text where !password.isEmpty else {
                return
     }
     self.registerUserAsync(email, password: password)
}