Context:
I have a custom Day Struct which internally uses a Swift Date Property. I would this Struct be able to check, if another given day is the same weekday as the Day Struct itself. However, every time this Code gets executed, my App freezes without any Runtime Error.
Code
struct Day: Hashable {
private let calendar: Calendar = .current
let date: Date
static func == (lhs: Day, rhs: Day) -> Bool {
return Calendar.current.isDate(lhs.date, inSameDayAs: rhs.date)
}
func isSameDayOfTheWeek(as day: Day) -> Bool {
// Replacing this Line to RETURN TRUE prevents the Crash.
return calendar.component(.weekday, from: self.date) == calendar.component(.weekday, from: day.date)
}
}
enum Time: Int16, Comparable, Identifiable, CaseIterable {
case morning, noon, evening, night
var id: Int16 { self.rawValue }
var name: String { ... }
}
struct ToDo: Hashable, Identifiable {
let id: UUID = UUID()
let block: Block // NSManagedObject
let day: Day
let time: Time
}
struct ToDoView: View {
@FetchRequest(sortDescriptors: [SortDescriptor(\.creationTS)]) private var blocks: FetchedResults<Block>
var body: some View {
ForEach(toDos) { toDo in
Text(toDo.name)
}
}
private var toDos: [ToDo] {
var toDos: [ToDo] = []
for block in blocks {
let startDay: Day = block.safeStartDay
var day: Day = .today
while day >= startDay {
// Removing this Line prevents the Crash.
guard startDay.isSameDayOfTheWeek(as: day) else { continue }
for time in Time.allCases {
toDos.append(ToDo(block: block, day: day, time: time))
}
day = day - 1
}
}
return toDos
}
}
Question
How can I solve this Crash and still be able to check if another given day is the same weekday as the Day Struct itself?