我为什么会收到以下错误“线程1:致命错误:在展开可选值时意外发现nil”

时间:2018-08-05 00:34:30

标签: ios swift uidatepicker

我试图将UIDatePicker的date属性分配给类型为Date的变量。我收到错误:-

  

线程1:致命错误:展开包装时意外发现nil   可选值

这是有问题的代码:

import UIKit
import RealmSwift

class AddPayDateViewController: UIViewController {

    let realm = try! Realm()
    var selectedDate = Date()
    @IBOutlet weak var myDatePicker: UIDatePicker!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func datePickerDateChanged(_ sender: Any) {

        selectedDate = myDatePicker.date
        print("The date selected is \(myDatePicker.date)")

    }
}

1 个答案:

答案 0 :(得分:0)

可以请您尝试

if let date = myDatePicker.date {

    self.selectedDate = date 

}