Tom Hamming Tom Hamming - 11 months ago 61
iOS Question

Translate NSCalendar.weekdaySymbols index to NSDateComponents.weekday

I'm writing a feature of my iOS app that involves scheduling weekly repeating local notifications on particular days of the week. I'd like to use the

APIs properly so I don't assume things I shouldn't. But I don't see any property on
about how many days there are in a week.

I'm displaying days of the week using
, and letting the user choose which days they want notifications on. Then I'm scheduling local notifications based on that.

The real question is: How do I translate a day's index in
into the value I give to

Answer Source

This is a bit of a simplification, but you can think of days of the week as belonging to the Gregorian calendar, independent of what calendar is actually in use. Those calendars largely govern day/month/year arithmetic, with the days of the week proceeding independently of the particulars of each calendar's number and length of months.

If you accept that as a given, then you just need to correct for the off-by-one difference between a calendar's weekdaySymbols (indexed from 0 to 6) and NSDateComponents.weekday (a value from 1 to 7).

extension DateComponents {     // NSDateComponents in Swift < 3
    func weekdaySymbol(in calendar: Calendar) -> String? {
        guard let weekday = self.weekday else { return nil }
        return calendar.weekdaySymbols[weekday - 1]