0

I am trying to code an if statement to display text on my label but I want to use two text field variables. It shows no error but when I press the button on the simulator or device the label still shows up blank.

I am just starting coding so I'm guessing it has an easy answer.

Here is my coding:

   @IBOutlet var LblResult: UILabel!
   @IBAction func Calculate(_ sender: UIButton)
{
    let Variable1 = (Variable1.text! as NSString).floatValue 

  *//var 1 and 2 are text fields*

    let Variable2 = (Variable2.text! as NSString).floatValue

    if Variable1 > 15 && Variable2 < 30{
        LblResult.text = "TEXT"
    }
  }

2 Answers 2

1

You should be doing it like this in Swift.

if let text1 = CGFloat(variable1.text!), let text2 = CGFloat(variable2.text!), text1 > 15, text2 < 30 {
    lblResult.text = "TEXT"
}

A few things to note

  • variables should be in lowerCamelCase.
  • text from UITextField can be force-unwrapped. They always return at least "".
  • Use String instead of NSString in Swift.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Works great!
1

You can try this:

// Using a guard statement is a safe way to unwrap optionals
guard let text1 = Variable1.text else { return }
guard let text2 = Variable2.text else { return }

if (Float(text1) > 15) && (Float(text2) < 30) {
    LblResult.text = "TEXT"
}

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.