Reputation: 119
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
Reputation: 2122
This code always triggers a runtime error when text is nil.
Please follow this to handle optional.
Upvotes: 2
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
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