Search code examples
swiftstringinteger

Converting String to Int with Swift


The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the values in the text boxes are string, I am unable to convert them to integers.

@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

Solution

  • Basic Idea, note that this only works in Swift 1.x (check out ParaSara's answer to see how it works in Swift 2.x):

        // toInt returns optional that's why we used a:Int?
        let a:Int? = firstText.text.toInt() // firstText is UITextField
        let b:Int? = secondText.text.toInt() // secondText is UITextField
    
        // check a and b before unwrapping using !
        if a && b {
            var ans = a! + b!
            answerLabel.text = "Answer is \(ans)" // answerLabel ie UILabel
        } else {
            answerLabel.text = "Input values are not numeric"
        }
    

    Update for Swift 4

    ...
    let a:Int? = Int(firstText.text) // firstText is UITextField
    let b:Int? = Int(secondText.text) // secondText is UITextField
    ...