Converting String to Int with Swift

前端 未结 30 1610
小鲜肉
小鲜肉 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:02

    An Int in Swift contains an initializer that accepts a String. It returns an optional Int? as the conversion can fail if the string contains not a number.

    By using an if let statement you can validate whether the conversion succeeded.

    So your code become something like this:

    @IBOutlet var txtBox1 : UITextField
    @IBOutlet var txtBox2 : UITextField
    @IBOutlet var txtBox3 : UITextField
    @IBOutlet var lblAnswer : UILabel
    
    @IBAction func btn1(sender : AnyObject) {
    
        let answer1 = "The acceleration is"
        var answer2 = txtBox1
        var answer3 = txtBox2
        var answer4 = txtBox3
    
        if let intAnswer = Int(txtBox1.text) {
          // Correctly converted
        }
    }
    

提交回复
热议问题