Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How do I convert a string to an integer in Swift 2.0?

My code is as follows, Im trying to build a calculator application

@IBAction func addBtn(sender: AnyObject) {
        var num1 = textBox.text
        print("The First Number Is\(num1)")
        textBox.text = ""
        var num2 = textBox.text
        print("The Second Number Is\(num2)")
        textBox.text = ""
        var ans = num1 + num2 //These need to be integers so I can add them.
        println("The Answer Is\(ans)")

    }

1 Answer

Hello :

What you want to do is cast these into the type Int.

Int(textBox.text)

Now they will return as an optional, so make sure you do the right procedure to unwrap them.

@IBAction func addBtn(sender: AnyObject) {
        var num1 = Int(textBox.text)
        print("The First Number Is\(num1)")
        textBox.text = ""
        var num2 = Int(textBox.text)
        print("The Second Number Is\(num2)")
        textBox.text = ""
        var ans = num1 + num2 //These need to be integers so I can add them.
        println("The Answer Is\(ans)")

    }