what\'s the easiest way to add the value of two textField
to equal a sum to a label.
Here are the text fields and label I am using:
@IBOutlet we
You can use the power of functional swift like this:
if let textField1String = textField1.text, let textField2String = textField2.text {
let arr = [textField1String, textField2String]
let result = arr.compactMap({ Int($0) }).reduce(0, +) //Cast in Int value + using reduce to sum all the values of array
speedLabel.text = "\(result)"
}
This code will execute even if one of the textfields are empty or if a number isn't inputed inside and replace the invalid fields with 0
speedLabel.text = "\((Double(f1TextField.text ?? "0.0") ?? 0.0) + (Double(f2TextField.text ?? "0.0") ?? 0.0))"
If you have numbers on there use this:
if let num1 = Double(f1TextField.text!), let num2 = Double(f2TextField.text!) {
speedLabel.text = "\(num1 + num2)"
}
Simplest one is this wether it contains text or not.
speedLabel.text = "\(f1TextField.text)\(f2TextField.text)"
print(speedLabel.text)