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'
comp.day -= 1
comp.day isn't an lvalue, it is just the return from a method called day on comp... in objective-C there is some magic to make properties work this way (ie it is different than a dot accessor of a classical obj c object), maybe that magic is turned off in swift 3 – Grady Playerfunc startOfWeek(_ weekday: Int? = 1) -> Date? { var cal = Calendar.current cal.firstWeekday = weekday ?? 1 let comp = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self) return cal.date(from: comp) }
– Leo Dabus