I tried to perform simple mathematical calculations based on input from several textfields. When one field is not filled in, I would like to continue the calculation for other fields. However, this does not work with my use of the (inappropriate?) guard
statement.
Put simply:
If field1 is filled in, perform calculation (i.e. multiply that amount by 0.5) and store the result.
If field2 is filled in, perform calculation (i.e. multiply that amount by 0.2) and store the result.
etc.
As an absolute beginner, I tried this:
@IBAction func calculate(_ sender: Any) {
//amount 1
guard let amount1 = textField1.text else{
return}
guard let amount1double = Double(amount1) else{
return}
var amt1 = amount1double
amt1 = amt1 * 0.5
//amount 2
guard let amount2 = textField2.text else{
return }
guard let amount2double = Double(amount2) else{
return }
var amt2 = amount2double
amt2 = amt2 * 0.2
}
The above code will stop if textField1 is not filled in. However I want the code to continue to calculate amount2 if textField1 is empty.
I read about if let
statements to maybe continue with the rest of the code after a nil
in the texfField, however I could not make it work. Furthermore I understand this will only allow me to access that value within that block.
The goal is to ultimately get the highest / maximum amount from all calculated amounts, if available.