FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

UITextField.text optional unwrap inside of textFieldShouldEndEditing function

Forums > Swift

Hello, Please help me understand why it's not calling else branch when empty(nil) input ? So, after input a text into a textField it returns data as expected:

    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {

        if textField.text == Optional("") {
            print("This is optional")
        } else { print ("This is \(textField.text) and not optional nil") }

        if let inputCity = textField.text {
            print("fuction to get city data - \(inputCity)")
            return true
        } else {
            print("Rise alert NO city entered")
            return false
        }
    }

OutPut:

This is Optional("Paris") and not optional nil
fuction to get city data - Paris

But when empty input entered, it does not call else as expected

This is optional
fuction to get city data - 

   

Because an empty string is still a string, not nil. So if let inputCity = textField.text unwraps textField.text and assigns its value ("") to inputCity and the first branch of your if else executes.

If you want to switch to the second branch when textField.text is either nil or an empty string, you can do this:

        if let inputCity = textField.text, !inputCity.isEmpty {
            print("fuction to get city data - \(inputCity)")
            return true
        } else {
            print("Rise alert NO city entered")
            return false
        }

   

Aaah, that's make sense... Great, thanks a lot. It's more clear now.

   

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.