what's the easiest way to add the value of two text fields to equal a sum to a label

試著忘記壹切 提交于 2020-01-30 13:27:15

问题


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 weak var f1TextField: UITextField!
@IBOutlet weak var f2TextField: UITextField!

@IBOutlet weak var speedLabel: UILabel!

I want to add f1TextField with f2TextField and show the result in the "speedLabel".


回答1:


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



回答2:


If you have numbers on there use this:

if let num1 = Double(f1TextField.text!), let num2 = Double(f2TextField.text!) {
    speedLabel.text = "\(num1 + num2)"
}



回答3:


Simplest one is this wether it contains text or not.

speedLabel.text = "\(f1TextField.text)\(f2TextField.text)"
    print(speedLabel.text)



回答4:


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


来源:https://stackoverflow.com/questions/50099803/whats-the-easiest-way-to-add-the-value-of-two-text-fields-to-equal-a-sum-to-a-l

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!