简体   繁体   中英

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

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!

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
}

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
}

对于更紧凑的解决方案,另一种选择是使用flatMap:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM