mk64 mk64 - 5 months ago 22x
Swift Question

Stanford Calculator app keeps crashing

I'm taking the Stanford iPad and iPhone developer course online at Stanford using Swift and working on creating a Calculator application. (Still a bit new to programming.)

However, it keeps crashing with the error message whenever I select an operator from the calculator.

operandStack = [36.0]
fatal error: unexpectedly found nil while unwrapping an Optional value

and then when I look in ViewController to see what part of the source code is highlighted. It is this:

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

the error message under this though, reads:


I don't understand what's going on, since I entered the code, word for word from the lecture.

Any help is appreciated!

Thanks in advance!


I am stuck at that part of the course too!

I think that apple recently made changes to NSNumberFormatter's numberFromString method. Because when I printed out display.text!, there was nothing wrong. In other words, it does not found nil while unwrapping that part.

Another part we are unwrapping is here, at the second ! mark, we unwrap only this part:


But we have an error out of this, so numberFromString should be returning nil.

But in the videos, it doesn't. It perfectly turns floating point number strings (such as "36.0") to NSNumber, then to Double.

And since your question was asked on May 20th and I could not find any "old" questions, I think Apple had changed the code on numberFromString.

Edit: I did something crazy and used Find & Replace (command + F) to replace all "Double"s to "Int"s in my code. The multiplication part works well now, I think the problem is about the "." part on Doubles.

Edit 2: I solved it. Some countries such as US use "." to separate decimals and some others such as Turkey use "," to do it. It works on video because he's doing it on US.

NSNumberFormatter has a property called decimalSeparator. We have to set it to ".". I did the following changed to my code and it worked perfect.

var displayValue: Double {
    get {
        var formatter = NSNumberFormatter()
        formatter.decimalSeparator = "."
        return (formatter.numberFromString(display.text!)!.doubleValue)
    set {
        display.text = "\(newValue)" 
        userIsInTheMiddleOfTypingNumber = false