Converting String To Int With Swift


Answer :

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 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
...


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 integer's 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


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable