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

3k Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

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