Converting String to Int with Swift

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

    Swift 3

    The simplest and more secure way is:

    @IBOutlet var textFieldA  : UITextField
    @IBOutlet var textFieldB  : UITextField
    @IBOutlet var answerLabel : UILabel
    
    @IBAction func calculate(sender : AnyObject) {
    
          if let intValueA = Int(textFieldA),
                let intValueB = Int(textFieldB) {
                let result = intValueA + intValueB
                answerLabel.text = "The acceleration is \(result)"
          }
          else {
                 answerLabel.text = "The value \(intValueA) and/or \(intValueB) are not a valid integer value"
          }        
    }
    

    Avoid invalid values setting keyboard type to number pad:

     textFieldA.keyboardType = .numberPad
     textFieldB.keyboardType = .numberPad
    

提交回复
热议问题