When is dateByAddingComponents: toDate: options return nil?

I used dateByAddingComponents:toDate:options: and dateByAddingUnit:value:toDate:options: and used an optional binding to get the date from it. Like this:

 guard let startOfNextMonth = calendar.dateByAddingComponents(oneMonthComponent, toDate: startOfThisMonth, options: []) else { return nil } 

Where oneMonthComponent is just an NSDateComponent whose month value is 1.

When I read about this, in the documentation they both say something like:

Returns nil if the date falls outside the specified receiver range or if the calculation cannot be performed.

And I was wondering when it was definitely triggered. If I just add a month to the date, is there a way that can ever be null? Is it because there are some differences in other calendar systems, where adding some units does not make sense?

I searched around and could not find an instance where it would return zero.

Is there anything that the code above could do, zero? What is an example of adding components to nil?

+6
source share
1 answer

In practice, if you just add a month to the date, you will not get the nil value.

However, you can get the nil value in some degenerative situations. For example, if you use the Islamic calendar and add -9,999,999 years, you will get nil (although, which is curious, but not in other calendars). Other calendars often overflow / end the year in these extreme situations (even if you expect them to return nil , given the documentation you provided).

Personally, I suspect that there are currently very few situations where you get nil values. I tried all kinds of extreme values, and the Islamic calendar was the only one that I managed to get the value of nil . However, this does not mean that Apple may not add a more robust logic for checking dates in the future. We will probably have to get advice from Apple (or see the source code for NSCalendar ) to finally answer this question.

So, on the bottom line, I would suggest keeping your guard statement, but it is unlikely to fail in real-world scenarios.

+3
source

All Articles