-2

I'm following the Stanford classes about iOS 8 development. I have some questions about my code. There is my whole code.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var display: UILabel!
    var userIsEnterADigit = false
    @IBAction func appendDigit(sender: UIButton) {
        let digit = sender.currentTitle!
        if userIsEnterADigit{
            display.text = display.text! + digit
        }else{
            display.text = digit;
            userIsEnterADigit = true
        }
    }
    var operandStack = Array<Double>()

    @IBAction func enter() {
        userIsEnterADigit = false
        operandStack.append(displayValue)
        print("operandStack = \(operandStack)")
    }


    var displayValue :Double {

        get{
            return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
        }
        set{
            display.text = "\(newValue)"
            userIsEnterADigit = false
        }
    }
}

I don't know why xcode point

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

having the error:

unexpectedly found nil while unwrapping an Optional value

I check the code with video and don't find the reason. Can someone tell me why?

And help me to understand the newValue in display.text = "\(newValue)". (Why it can appear like this? Is this a grammar of swift?)

Alexey Pichukov
  • 3,377
  • 2
  • 19
  • 22
dwjdwj
  • 25
  • 6
  • Possible duplicate of [What does an exclamation mark mean in the Swift language?](http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language) – Eric Aya Mar 05 '16 at 09:05
  • It looks like you should read to start it https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309 – Alexey Pichukov Mar 05 '16 at 09:15

1 Answers1

1
  • ! means "this variable should not be nil at this stage. If it is, throw." Most likely your text cannot be turned into a number, and the function parsing it into one has a ! so it throws.
  • You second question is indeed a "new grammar". It's a succinct way to create strings without doing the old fashioned format-with-escapes-and-list-of-variables.
Carlos
  • 5,991
  • 6
  • 43
  • 82
  • I think the question might be more about where the variable `newValue` comes from, as it doesn't appear to be defined anywhere in the code. I'm not convinced that `戴王炯` has followed the tutorial closely enough – Russell Mar 05 '16 at 09:59