我有以下功能,我需要标签根据所选日期更新周数。日期选择由UIDatePicker完成。
如果我写print(pickedDate)我得到刚刚由UIDatePicker选择的日期,所以这似乎工作正常。 但是,如果我打印(selectedDate)我得到nil,因此公式中的错误致命错误:在展开Optional值时意外发现nil
这是我的代码:
func selectWeek () {
let formatter = DateFormatter()
let pickedDate = dateEntry.text
let selectedDate = formatter.date(from: pickedDate!)
if (weekTwoIntervalJan! ... weekThreeIntervalJan!).contains(selectedDate!) {
weekNrLabel.text = "Week 3"
}
else if (weekThreeIntervalJan! ... weekFourIntervalJan!).contains(selectedDate!) {
weekNrLabel.text = "Week 4"
}
else if (startDateFebDate! ... weekOneIntervalFeb!).contains(selectedDate!) {
weekNrLabel.text = "Week 1"
}
else if (weekOneIntervalFeb! ... weekTwoIntervalFeb!).contains(selectedDate!) {
weekNrLabel.text = "Week 2"
}
else if (weekTwoIntervalFeb! ... weekThreeIntervalFeb!).contains(selectedDate!) {
weekNrLabel.text = "Week 3"
}
else if (weekThreeIntervalFeb! ... weekFourIntervalFeb!).contains(selectedDate!) {
weekNrLabel.text = "Week 4"
}
else {
print("fail")
}
你的UIDatePicker
的名字是什么?
也许你想做(用datePicker
的名字取代UIDatePicker
):
let selectedDate = datePicker.date