Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.toInt() removed in Swift 2?

Tags:

swift

swift2

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?

like image 647
Amit Kalra Avatar asked Jun 09 '15 17:06

Amit Kalra


2 Answers

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) 
like image 108
Jojodmo Avatar answered Oct 04 '22 05:10

Jojodmo


Swift 2

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

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

like image 24
toddsalpen Avatar answered Oct 04 '22 05:10

toddsalpen