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

前端 未结 4 1001
误落风尘
误落风尘 2021-01-29 14:17

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         


        
相关标签:
4条回答
  • 2021-01-29 14:47

    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)"
    }
    
    0 讨论(0)
  • 2021-01-29 14:48

    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))"
    
    0 讨论(0)
  • 2021-01-29 15:05

    If you have numbers on there use this:

    if let num1 = Double(f1TextField.text!), let num2 = Double(f2TextField.text!) {
        speedLabel.text = "\(num1 + num2)"
    }
    
    0 讨论(0)
  • 2021-01-29 15:05

    Simplest one is this wether it contains text or not.

    speedLabel.text = "\(f1TextField.text)\(f2TextField.text)"
        print(speedLabel.text)
    
    0 讨论(0)
提交回复
热议问题