.toInt() removed in Swift 2?

52.9k views Asked by At

I was working on an application that used a text field and translated it into an integer. Previously my code

textField.text.toInt() 

worked. Now Swift declares this as an error and is telling me to do

textField.text!.toInt()

and it says there is no toInt() and to try using Int(). That doesn't work either. What just happened?

5

There are 5 answers

8
Jojodmo On BEST ANSWER

In Swift 2.x, the .toInt() function was removed from String. In replacement, Int now has an initializer that accepts a String

Int(myString)

In your case, you could use Int(textField.text!) insted of textField.text!.toInt()

Swift 1.x

let myString: String = "256"
let myInt: Int? = myString.toInt()

Swift 2.x, 3.x

let myString: String = "256"
let myInt: Int? = Int(myString)
0
Nathan On

Its easy enough to create your own extension method to put this back in:

extension String {
    func toInt() -> Int? {
        return Int(self)
    }
}
0
ЯOMAИ On

That gave me some errors too!

This code solved my errors

let myString: String = dataEntered.text!  // data entered in textField
var myInt: Int? = Int(myString)    // conversion of string to Int

myInt = myInt! * 2  // manipulating the integer sum,difference,product, division 

finalOutput.text! = "\(myInt)"  // changes finalOutput label to myInt
1
toddsalpen On

Swift 2

let myString: NSString = "123"
let myStringToInt: Int = Int(myString.intValue)

declare your string as an object NSString and use the intValue getter

0
Swikar On

I had the same issued in Payment processing apps. Swift 1.0

let expMonth = UInt(expirationDate[0].toInt()!)
let expYear = UInt(expirationDate[1].toInt()!)

After in Swift 2.0

let expMonth = Int(expirationDate[0])
let expYear = Int(expirationDate[1])