1

I tried running below statement, but it's skipped right over in the code.

guard let num1 = num1Input.text else
{
    show("No input in first box")
    return
}

Can somebody tell me why this statement isn't running when the text field is blank?

Liju Thomas
  • 1,054
  • 5
  • 18
  • 25

3 Answers3

3

You could use the where clause to check for non-nil and non-empty

guard let num1 = num1Input.text where !num1.isEmpty else {
    show("No input in first box")
    return
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0

You should check the length of the text, not if its nil i.e:

guard num1Input.text.characters.count > 0 else {
  ...
}

If the text is optional, you can do.

guard let num1 = num1Input.text where num1.characters.count > 0 else {
  ...
}
sbarow
  • 2,759
  • 1
  • 22
  • 37
0

This statement is testing whether the text is nil but you probably want to test whether the string is empty, therefore

guard let input = num1Input.text where input.characters.count > 0 else {
    print("empty")
    return
}

or just simply

guard num1Input.text?.characters.count > 0 else {
    print("empty")
    return
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270