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

前端 未结 4 1008
误落风尘
误落风尘 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)"
    }
    

提交回复
热议问题