Converting String to Int with Swift

前端 未结 30 1293
小鲜肉
小鲜肉 2020-11-22 06:59

The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the value

30条回答
  •  悲&欢浪女
    2020-11-22 07:17

    Use this:

    // get the values from text boxes
        let a:Double = firstText.text.bridgeToObjectiveC().doubleValue
        let b:Double = secondText.text.bridgeToObjectiveC().doubleValue
    
    //  we checking against 0.0, because above function return 0.0 if it gets failed to convert
        if (a != 0.0) && (b != 0.0) {
            var ans = a + b
            answerLabel.text = "Answer is \(ans)"
        } else {
            answerLabel.text = "Input values are not numberic"
        }
    

    OR

    Make your UITextField KeyboardType as DecimalTab from your XIB or storyboard, and remove any if condition for doing any calculation, ie.

    var ans = a + b
    answerLabel.text = "Answer is \(ans)"
    

    Because keyboard type is DecimalPad there is no chance to enter other 0-9 or .

    Hope this help !!

提交回复
热议问题