2016-03-05 87 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

相關問題