swiftswift2guard-statement

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


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

Solution

  • 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