Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code:

var displayValue: Double{
    get{
        println("display.text =(display.text!)")
        return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
    }
    set{
        display.text = "(newValue)"
        userIsInTheMiddleOfTypingANumber = false;
    }
}

It works fine in the simulator. but when I try it on phone it crashes. here is the console:

digit= 3
display.text =3
operandStack =[3.0]
digit= 2
display.text =2
operandStack =[3.0, 2.0]
display.text =6.0
fatal error: unexpectedly found nil while unwrapping an Optional value

This line:

NSNumberFormatter().numberFromString(display.text!)!

is returning nil which causing the app to crash cause it couldn't unwrap the optional. I really don't know what's wrong. I'm following some tutorials in iTunes U.

any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
748 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try:

get{
    println("display.text =(display.text!)")
    let formatter = NSNumberFormatter()
    formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    return formatter.numberFromString(display.text!)!.doubleValue
}

Because, NSNumberFormatter uses devices locale by default, it's possible that the decimal separator is not ".". For example:

let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "ar-SA")
print(formatter.decimalSeparator!) // -> outputs "?"
formatter.numberFromString("6.0") // -> nil

The formatter that uses such locales cannot parse strings like "6.0". So if you want consistent result from the formatter, you should explicitly specify the locale.

As for en_US_POSIX locale, see the document:

In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences. en_US_POSIX is also invariant in time (if the US, at some point in the future, changes the way it formats dates, en_US will change to reflect the new behavior, but en_US_POSIX will not), and between platforms (en_US_POSIX works the same on iPhone OS as it does on OS X, and as it does on other platforms).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...