I have created a NSManagedObject sReminderDate: Date(). This is stored in the coreData. The value for this comes from the date and time set by the user from the datePicker.
When the viewcontroller is loaded, this value is compared with the currentDate and time and if the currentTime > sReminderDate then a label says "Time's Up". The issue is that when the user loads the viewcontroller for the first time, the time and date is not set the sReminderDate is 'null'. Hence, it's crashing my app because this is null and I am using it for comparison.
I am having a hard time unwrapping it with if-let and guard statements. Help would be appreciated!
let currentDate = NSDate() //Current date and time stored whenever viewcontroller is loaded
if ((currentDate as! Date ) >= (editnotes?.sSelectedDate)! && (editnotes?.sReminderState == true)) //Comparison -> sSelectedDate is the date stored in coreData by the user when scheduling task
{
editnotes?.sReminderDate = "Time is up"
reminderMsg.text = editnotes?.sReminderDate
}
Look what you wanna to achieve is to separate code when you don't have this values and when you got them and can compare, i.e. implement your logic
I'd make something like that:
guard let selectedDate = editnotes?.sSelectedDate,
let needsToRemind = editnotes?.sReminderState else {
// implement logic when you DO NOT have values
return
}
// Everything is cool and you have values => can compare
if selectedDate < Date() && needsToRemind {
editnotes?.sSelectedDate = "Time's up"
// Possibly editnotes?.sReminderDate better to unwrap somehow
// if-let, guard-let, ??
reminderMsg.text = editnotes?.sReminderDate
}
Code is much cleaner and more representative