Reputation: 39
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
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
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
text
from UITextField
can be force-unwrapped. They always return at least "".String
instead of NSString
in Swift.Upvotes: 1