Optionals instead of forced unwrap for ago/later?
Closed this issue ยท 3 comments
Thanks for a great library and updating the code base. It much slimmer and leveraging more native API's ๐
I noticed in the updates there are a lot of optionals now, which are a bit inconvenient although I understand why. Any ideas on safely getting around this and not have Timepiece
return optionals for at least ago/later
calculations?
For example, 46.days.later
return a Date?
object because it is using Calendar.current.date(byAdding: -self, to: Date())
.
Expanding this, the source is really this:
var dayComponents = DateComponents()
dayComponents.day = 46
return Calendar.current.date(byAdding: dayComponents, to: Date()) //Optional
How is it possible the Calendar.current.date(byAdding:to:)
would ever be nil
, such as what scenario could this happen? I can't think of any if the DateComponent
is instantiated in a controlled manner by the library and both components are always valid. So would it be safe enough for the sake of convenience to force unwrap it like this?:
var later: Date {
return Calendar.current.date(byAdding: self, to: Date())!
}
Thank you for the issue ๐ .
I feel that it is a bit inconvenient too. I don't understand when the return value of date(byAdding:to:)
is nil
. But, this library shouldn't force unwrapping because this library doesn't know any given input. Instead, an user who knows input should force unwrapping.
What do you think?
I share your concern and position. It would be helpful to know what kind of input would cause a nil to make a better decision about this, and how to recover from it so we can guard it. I hope someone can chime in, and will try to look around in the meantime as well. Thanks for the input!
@basememara I will try to read the implementation from here. If I know when the return value of date(byAdding:to:)
is nil
and ensure that this ago
/later
always doesn't return nil
, I will remove the optionals.