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

人盡茶涼 提交于 2020-01-13 19:56:09

问题


I got fatal error While using guard let. Here's the error:

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

Below my code which i have used:

@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)
}

回答1:


You should be very carefull with optionals. Using ! you tell to Swift compiler that you can guarantee that the value is exists. Try to do it like this:

@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”.

More about optionals you can find here https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309




回答2:


You are unwrapping the optional what makes the binding meaningless and causes the error:

emailTextField.text! // see the exclamation mark

The error message says that the conditional binding must be optional (the text property is optional by default), so just delete the exclamation mark:

emailTextField.text

An easier syntax is isEmpty and you can reduce the code to one guard statement.

@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)
}


来源:https://stackoverflow.com/questions/37858071/guard-let-error-initializer-for-conditional-binding-must-have-optional-type-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!