1

So when I press the button I check if both the UITextField and the UITextView have some value inside them, but if they are nil then perform this.

So I tried this, but it didn't work:

@IBOutlet weak var defTextView = UITextView

@IBAction func btnTapped(sender: UIButton) {

    if let definitionName = defTextView.text {

        print(definitionName)

    } else {

        print("nil")

    }
}

Instead of receiving the word "nil" I got empty Strings bring printed

4 Answers 4

4

defTextView.text is empty String "" instead of nil.

Try where clause to check if it is empty:

@IBOutlet weak var defTextView = UITextView

@IBAction func btnTapped(sender: UIButton) {

    if let definitionName = defTextView.text where !definitionName.isEmpty {

        print(definitionName)

    } else {

        print("nil")

    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your code should work, however, remember that an empty string is not nil. A UITextView's text is unlikely to be nil, so I would use an if statement to check if it is an empty string, as well as than if let unwrapping.

For example, use this instead:

if let defenitionName = defTextView.text where defTextView.text != nil {
  print(definitionName)
} else {
  print("none") //Not necessarily nil.
}

Comments

0

try following code

if defTextView.text != nil || !(defTextView.text == "")  {

    print(definitionName)

} else {

    print("nil")

}

1 Comment

I tried it with just if !(defTextView.text == "") {} and it worked thanks!
0

The question is actually meaningless because the text of a text view is never nil.

According the documentation the property text of UITextView is an implicit unwrapped optional - unlike UILabel whose text can be nil.

So it's guaranteed to be not nil when it's used and you need only to check for an empty string, optional binding or != nil is not needed.

@IBAction func btnTapped(sender: UIButton) {

   let definitionName = defTextView.text
   if definitionName.isEmpty {
      print("definitionName is empty")
   } else {
      print("definitionName is not empty")
   }
}

Comments

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.