2016-03-05 84 views
-2

我正在关注斯坦福大学关于iOS 8开发的课程。我有一些关于我的代码的问题。有我的整个代码。Swift意外地发现零,同时展开一个可选值

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 
     } 
    } 
} 

我不知道为什么Xcode的点

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

具有错误:

unexpectedly found nil while unwrapping an Optional value

我请与视频代码,没有找到原因。有人能告诉我为什么吗?

并帮助我了解newValuedisplay.text = "\(newValue)"。 (为什么它会出现这样的情况?这是一种快速语法吗?)

+0

可能重复[Swift语言中感叹号的含义是什么?](http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-迅速语言) – Moritz

+0

看起来你应该阅读启动它https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097- CH5-ID309 –

回答

1
  • !意思是“这个变量在这个阶段不应该是零,如果是的话,抛出。”很可能你的文本不能被转换成数字,并且解析成一个的函数有一个!所以它抛出。
  • 你的第二个问题确实是一个“新的语法”。这是没有做老式旧格式与 - 逃逸和列表-的变量来创建一个字符串简洁的方式。
+0

我想这个问题可能会更了解其中变量'newValue'从何而来,因为它不会出现要在代码的任何地方定义。我不相信'戴王炯'已经紧跟着这篇教程 – Russell

相关问题