Mr_Username
Mr_Username

Reputation: 119

When my textfield is empty, my app crashes how do I respond to an empty text field?

I have a textfield in my app that interacts with a button. When i type nothing into the text field, my app crashes. To fix this, i've tried the following:

if textField.text!.isEmpty {

        iLabel.text = "Please type something"

    }

However, this does not work. Can someone please point out my flaws and how to fix this issue?

Upvotes: 1

Views: 1252

Answers (3)

Suresh Thayu
Suresh Thayu

Reputation: 2122

This code always triggers a runtime error when text is nil.

Please follow this to handle optional.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

Upvotes: 2

Jeet
Jeet

Reputation: 5659

code mostly looks ok, however are you sure your text field is mapped with the outlet in code. Missing the outlet mapping is major cause for application crashing even the code is fine.

This case you are force unwrapping the textField by doing textfield.text! and if the mapping to outlet is missing it would crash the application.

Upvotes: 2

Sam
Sam

Reputation: 956

Its crashing because textField.text is nil so you can't call isEmpty on it. Just check

if textField.text == nil {
    //textField is empty
}

Upvotes: 2

Related Questions