Unwrapping NSNumber works fine in iOS Simulator but unexpectedly found nil on iPhone

Hello,


I've just began learning Swift and iOS Delevopment. Until now everything worked fine in the iOS Simulator or in Playground. But when testing the app on my iPhone ("Build and then run the current scheme") there's this fatal error:


fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)


I could shrank down the code to the following:


var stack = Array<String>()
stack.append("2.3")
let lastElement = stack.popLast()!
print("Popped last element: \(lastElement)")
let number = NSNumberFormatter().numberFromString(lastElement)
print("NSNumber gives us: \(lastElement)")
let doubleValue = number!.doubleValue
print("Double value of this element is: \(doubleValue)")


Playground as well as the iOS Simulator (iPhone 6, iOS 9.1) work fine and show:


Popped last element: 2.3
NSNumber gives us: 2.3
Double value of this element is: 2.3


But when using my iPhone it shows:


Popped last element: 2.3
NSNumber gives us: 2.3
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)


When I change my code on line 07. to

let doubleValue = number?.doubleValue

then it shows

Popped last element: 2.3
NSNumber gives us: 2.3
Double value of this element is: nil


Can someone explain to me why everything works fine both in Playground and the iOS Simulator (and the result is 2.3) and on my iPhone the result is nil and throws a fatal error?


Thanks in advance!


Robert

Accepted Reply

Your phone is probably set to a region where the decimal separator is a comma rather than a period, so the parsing fails.


If your number strings are always coming in the same format (e.g. from a web service you control), then you should set the locale explicitly on the number formatter, rather than using the device default. If the numbers are coming from user input, then you should respect the locale, and you will need to handle the case where it doesn't parse as a valid number anyway.

Replies

Your phone is probably set to a region where the decimal separator is a comma rather than a period, so the parsing fails.


If your number strings are always coming in the same format (e.g. from a web service you control), then you should set the locale explicitly on the number formatter, rather than using the device default. If the numbers are coming from user input, then you should respect the locale, and you will need to handle the case where it doesn't parse as a valid number anyway.

Thank you! Yes, my iPhone was set to German where the decimal separator is a comma. I never thought about that because it worked flawlessly in the iOS Simulator and my Mac is set to German as well. I now set the local explicitly and it works 🙂