Bpython
Bpython

Reputation: 39

How to use two let variables in an if statement in swift

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"
    }
  }

Upvotes: 0

Views: 87

Answers (2)

droberson
droberson

Reputation: 43

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"
}

Upvotes: 1

Rakesha Shastri
Rakesha Shastri

Reputation: 11243

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.

Upvotes: 1

Related Questions