.toInt() removed in Swift 2?

SwiftSwift2

Swift Problem Overview


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?

Swift Solutions


Solution 1 - Swift

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)

Solution 2 - Swift

Swift 2

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

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

Solution 3 - Swift

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

extension String {
    func toInt() -> Int? {
        return Int(self)
    }
}

Solution 4 - Swift

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])

Solution 5 - Swift

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmit KalraView Question on Stackoverflow
Solution 1 - SwiftJojodmoView Answer on Stackoverflow
Solution 2 - SwifttoddsalpenView Answer on Stackoverflow
Solution 3 - SwiftNathanView Answer on Stackoverflow
Solution 4 - SwiftSwikarView Answer on Stackoverflow
Solution 5 - SwiftЯOMAИView Answer on Stackoverflow