0

I would like to check if textField is empty or not and if empty, give specific text. I tried like below but it returns ""

let text = textField.text ?? "abc"
let value = ["text": text]
//put firebase database
ref.child("text").setValue(value)

How can I fix this? Thank you in advance!

1
  • you can use placeholder property to set default text when textfield is empty. Commented Feb 3, 2018 at 11:59

3 Answers 3

3

The problem is you always get an empty string that's not nil. You can correct that as following:

let text = (textField.text ?? "").isEmpty ? "abc" : textField.text
Sign up to request clarification or add additional context in comments.

5 Comments

In that case you have to keep in mind that you end up with an optional String though.
If you don't want text to be an Optional String, simply force-unwrap the second occurrence of textField.text in this answer: let text = (textField.text ?? "").isEmpty ? "abc" : textField.text!.
Thank you for the comments! guard let text = (textField.text ?? "").isEmpty ? "abc" : textField.text else { return } I did like this. Is this bad approach?
With a guard like that you will return without doing anything if textfield.text is nil. If you want text to contain "abc" when textField.text is nil, that's not what you want.
You may just force unwrap it because the first condition already checks that the value not nil
1

You have to make sure that the text property is not nil and also that it does not contain an empty string:

let text: String
if let textFieldText = textField.text, !textFieldText.isEmpty {
    text = textFieldText
} else {
    text = "abc"
}

Comments

1

Modifying Anton's answer slightly, you could use:

let text = (textField.text ?? "").isEmpty ? "abc" : textField.text!

(Force-unwrapping the 2nd occurrence of textField.text so text isn't an optional.)

In that case force-unwrapping is safe because the first ?? "nil coalescing operator will have handled the case where textField.text == nil.

If you don't want to use a force-unwrap, break the conversion into 2 lines:

let required = str ?? ""
let text = required.isEmpty ? "abc" : required

Daibaku, the solution you showed in the comments:

guard let text = (textField.text ?? "").isEmpty ? "abc" : textField.text else { 
  return 
}
print(text)

Will return without executing the print statement (or whatever follows the guard) if textField.text == nil

1 Comment

Thank you so much for the very detailed explanation!! I tried unwrap it and it worked perfectly. Thank you for your kindness:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.