Search code examples
iosswiftuitextfieldxcode11

UITextField Programmatically won't convert into string or take any binary operators Xcode


Prior to having this issue, I was using storyboards and outlets for text fields. However, I found it easier to work on my app programmatically. Unfortunately, as I began to convert my app such as by programmatically making a text field I ran into some issues as I still have some functions such as my login function that was made for the text fields from the storyboards. I'm still new swift so any solutions would be helpful.

I declared my email text field as such:

    var emailTxt: UITextField! 

The other aspects of the email text field are as such in the view did load function:

    emailTxt = UITextField(frame: CGRect(x: 77.0, y: 306.0, width: 262, height: 34))
    emailTxt.backgroundColor = .white
    emailTxt.borderStyle = .roundedRect
    emailTxt.keyboardAppearance = .light
    emailTxt.keyboardType = .emailAddress
    emailTxt.placeholder = "Email"
    emailTxt.font = UIFont.systemFont(ofSize: 14.0)
    emailTxt.textColor = .systemGreen
    emailTxt.tintColor = .systemGreen
    emailTxt.delegate = self

    self.view.addSubview(emailTxt)

Text field functions outside the view did load:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
}

Finally the area where I get the issues.

First, it says that for the guard statement there must be an else statement.

Then it says (Binary operator '!=' cannot be applied to operands of type 'UITextField?' and 'String') Then in the else statement it says (Closure expression is unused)

Finally, in the auth statement it gives the error: Cannot convert value of type 'UITextField' to expected argument type 'String' while underlining the email

Here is the code for that:

    guard let email = emailTxt
    email != "",
    let password = passwordTxt
    password != ""
        else {
            AlertController.showAlert(self, title: "Missing Info", message: "Please fill out all fields")
            return

    }

    Auth.auth().signIn(withEmail: email, password: password, completion: {(user, error) in
        guard error == nil else {
            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }

Solution

  • Your error is self explanatory, you are trying to use the UITextField type as String. Here what you need to use is the .hasText property of UIKeyInput protocol which UITextField conforms to. Here's how:

    guard emailTxt.hasText,
    passwordTxt.hasText
        else {
            AlertController.showAlert(self, title: "Missing Info", message: "Please fill out all fields")
            return
    }
    let email = emailTxt.text!
    let password = passwordTxt.text!
    

    You can force unwrap the text of UITextField because it defaults to empty String "". Even if it's set to nil it returns an empty string.