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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.