Reputation: 314
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.
Upvotes: 3
Views: 1872
Reputation: 51911
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, buten_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).
Upvotes: 8