ios – Converting String to Int with Swift

ios – Converting String to Int with Swift

Updated answer for Swift 2.0+:

toInt() method gives an error, as it was removed from String in Swift 2.x. Instead, the Int type now has an initializer that accepts a String:

let a: Int? = Int(firstTextField.text)
let b: Int? = Int(secondTextField.text)

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

    // toInt returns optional thats 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

ios – Converting String to Int with Swift

myString.toInt() – convert the string value into int .

Swift 3.x

If you have an integer hiding inside a string, you can convertby using the integers constructor, like this:

let myInt = Int(textField.text)

As with other data types (Float and Double) you can also convert by using NSString:

let myString = 556
let myInt = (myString as NSString).integerValue

Leave a Reply

Your email address will not be published.