致命错误:在展开可选值时意外发现nil-为什么?

0 null optional swift

我对使用Swift进行编码非常陌生,我不太确定这里发生了什么-有人可以帮忙吗?

谢谢

import UIKit

class SecondViewController: UIViewController {

    var toDoItems:[String] = []


    @IBOutlet weak var toDoItem: UITextField!

    @IBAction func addItem(sender: AnyObject) {

        toDoItems.append(toDoItem.text)
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

        println(toDoItems)



    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 5

您的IBOutlet,极有可能toDoItem未成功绑定到UITextFieldInterface Builder中的。在Interface Builder中检查文本字段的出口,并确保已成功将其连接。

在此处输入图片说明

如果插座正确连接,则此问题的另一个候选来源是视图控制器本身的实例化。如果您以编程方式实例化它(例如SecondViewController()而不是storyboard.instantiateViewControllerWithIdentifier(...)),那也会导致此错误。