UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on 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 - 

2      

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
        }

2      

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

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.