Home > Mobile >  iOS diff in days using dateComponent(_:from:to:) - what does nil mean for the result day?
iOS diff in days using dateComponent(_:from:to:) - what does nil mean for the result day?

Time:05-19

I'm calculating the diff between two Dates:

let diff = Calendar.current.dateComponents([.day], from: oldDate, to newDate)

and I got a DateComponents as a result, in which the day property is an optional, the doc doesn't say it's guaranteed to have a non-nil day in this calculation, so I wonder if I can make the assumption that day will never be nil in this case, even if the two Date are the same, day should be 0 instead of nil; Or, is it possible to have a day which equals to nil?

Thanks!

CodePudding user response:

I'd say the contract for the function call is ambiguous. A DateComponent's properties are all optional. It seems like it should return a value in the days property when that's what you ask for, but I'd still code defensively.

I call the force-cast operator the "crash if nil" operator, because that's what it does.

  • Related