Search code examples
swift3nscalendar

Date Extensions in Swift 3


The below code is part of a Date extension. However, in Swift 3 I'm getting a few errors that won't go away. I've already changed "NSCalendar" to "Calendar":

func startOfWeek(_ weekday: Int?) -> Date? {
    guard
        let cal = Calendar.current,
        let comp: DateComponents = (cal as Calendar).components([.yearForWeekOfYear, .weekOfYear], from: self) else { return nil }
    comp.to12pm()
    cal.firstWeekday = weekday ?? 1
    return cal.date(from: comp)!
}
func endOfWeek(_ weekday: Int) -> Date? {
    guard
        let cal = Calendar.current,
        var comp: DateComponents = (cal as Calendar).components([.weekOfYear], from: self) else { return nil }
    comp.weekOfYear = 1
    comp.day -= 1
    comp.to12pm()
    return (cal as NSCalendar).date(byAdding: comp, to: self.startOfWeek(weekday)!, options: [])!
}

Lines 3 & 11: let cal = Calendar.current, Initializer for conditional binding must have Optional type, not 'Calendar'

Line 12: I had an error but fixed it by changing "let comp:" to "var comp:"

Line 14: comp.day -= 1 Error: Binary operator '-=' cannot be applied to operands of type 'Int?' and 'Int'

I'm not great with extensions, this code was adapted from an extension I found online, so now updating this is proving to be difficult. Any suggestions?

Troubleshooting (things I tried):

let cal = Calendar?.current,

Error: Type 'Calendar?' has no member 'current'

let cal: Calendar? = Calendar.current,

Error: Explicitly specified type 'Calendar?' adds an additional level of optional to the initializer, making the optional check always succeed

let cal = Calendar.current?,

Error: Cannot use optional chaining on non-optional value of type 'Calendar'


Solution

  • My date extensions in Swift 3, based on the comments from @LeoDabus

    func startOfWeek(_ weekday: Int? = 1) -> Date? {
        var cal = Calendar.current
        cal.firstWeekday = weekday ?? 1
        let comp = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
        comp.to12pm()
        return cal.date(from: comp)
    }
    func endOfWeek(_ weekday: Int) -> Date? {
        let cal = Calendar.current
        var comp = cal.dateComponents([.weekOfYear], from: self)
        comp.weekOfYear = 1
        comp.day? -= 1
        comp.to12pm()
        return cal.date(byAdding: comp, to: self.startOfWeek(weekday)!)!
    }
    

    Note I am still mid-migration, so I can only confirm that these eliminate the errors and cannot test them in production yet.