37032

How do you convert optional text input to Int in Swift 2, Xcode 7 beta using if let - toInt does not

I'm having trouble converting optional input String to Int in order to do calculations on it.

let odoField = UITextField() // allows entry of text to iOS field odoField.text = "12500" // simulated input let odoString = odoField.text // now here is where I get trouble... if let odoInt = odoString.toInt() { distance = Double(odoInt) }

Apparently the toInt suffix is no longer part of Swift. I have tried the following:

if let odoInt = Int(odoString)() {

But then I get the error "Optional type String? is not unwrapped" and a suggestion to put a ! or ?, as in:

if let odoInt = Int(odoString!)() {

But then I STILL get the euro about unwrapping, with the suggestion that I add yet another !, then when I do that, another error that I get rid of the parens, like this:

if let odoInt = Int(odoString!)! {

And then I get ANOTHER error that "Initializer for conditional binding must have Optional type, not 'Int'."

I'm trying to create conditional unwrapping, here.

Help!

Answer1:

First thing to understand is that UITextField.text returns an optional string, so in your code, odoString is of type String?. Also, keep in mind that the Int constructor takes a String, not a String? so you have to unwrap the String? before you can use it. Just putting a ! after the variable (as in Int(odoString!)) will crash your app if the odoString is nil. Better would be something like this:

if let s = odoString, odoInt = Int(s) { // odoInt is of type Int. It is guaranteed to have a value in this block }

Answer2:

I've tested Daniel T's answer and it worked.

I have a situation where I want to get the result of a text field back as an optional Int. You can extend this to cover your case using the following code:

let odoInt = odoField.text != nil ? Int(odoField.text!) : nil if let odoInt = odoInt { // Use unwrapped odoInt here }

Answer3:

Another option - for a more compact solution - is to use a flatMap:

let number = odoString.flatMap { Double($0) } ?? 0.0

Answer4:

In fact, it appears that the answer in Swift 2 (Xcode 7 beta 6) is simpler than anything above. The code does not choke on a nil value for odoString when I do e.g. the following:

if let odoInt = Int(odoString!) { distance = Double(odoInt) }

I therefore surmise, barring deeper knowledge to the contrary, that the compiler does treat this as "if the statement is True (the right side is valid), then define and initialize the variable, and continue with execution." I welcome further feedback. This does render unnecessary a lot of the extra code that is suggested above.

Recommend

  • Connecting/disconnecting to/from an Chromecast Device with Swift
  • HTML5 number input field with currency symbol in the end of it
  • How to send Mandrill message with special characters?
  • Haskell: Functor instance for newtype
  • How to play NSData from Core Data in AVAudioPlayer
  • Spring 3 MVC: How to store € symbol from form?
  • Opencart minimum order price exclude one category
  • Invoke anonymous methods
  • Implementing module pattern in Javascript with dependency on jquery
  • How do I not borrow an Option when matching?
  • grep: matching on literal “+”
  • Using sed to extract string values
  • how to handle large size of update query in mysql with laravel
  • d3js: time scaling and “1901”
  • How to show a specific VC , more like navigate to a stack of VC
  • Get the negative of an Optional Chain
  • substitute period from abbreviation (single letter + period) unless followed by a capital letter
  • No such module 'Parse' following Parse iOS Swift Quickstart guide
  • Visual studio alerts workspace already exists
  • Adding independent aspx/asmx pages into DotNetNuke
  • Pythons argparse default value doesn't work
  • Cypher - matching two different possible paths and return both
  • How can we prepend rows to a react native list-view?
  • how do i write assembly code from c#?
  • Scipy Leastsq Optional Output Variable (Mesg)
  • x64 applications using gdi+: what are the consequences on performance?
  • Java: can you cast Class into a specific interface?
  • swift auto completion not working in Xcode6-Beta
  • AES padding and writing the ciphertext to a disk file
  • Updating server-side rendering client-side
  • How to extract text from Word files using C#?
  • Alternatives to the OPTIONAL fallback SPARQL pattern?
  • Hits per day in Google Big Query
  • Angular 2 constructor injection vs direct access
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • Linking SubReports Without LinkChild/LinkMaster
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • UserPrincipal.Current returns apppool on IIS