Skip to content

Instantly share code, notes, and snippets.

@colinfwren
Created November 19, 2023 21:29
Show Gist options
  • Save colinfwren/c633f1f283aaed8e57930100447fe4a4 to your computer and use it in GitHub Desktop.
Save colinfwren/c633f1f283aaed8e57930100447fe4a4 to your computer and use it in GitHub Desktop.
Date Test Approach 2 fetchMonthData and fetchYearData
func fetchMonthData() {
do {
let calendar = Calendar.init(identifier: .iso8601)
let date = calendar.date(from: DateComponents(year: year, month: month: day: 1))!
let weekOfMonth = calendar.component(.weekOfMonth, from: date)
var predicate: Predicate<ApproachModel>
if (weekOfMonth == 0) {
let weekOfYear = calendar.component(.weekOfYear, from: date)
predicate = #Predicate { todo in
((todo.year == year && todo.month == month) || (todo.week == weekOfYear)) && todo.shownInMonth == true
}
} else {
predicate = #Predicate { todo in
todo.year == year && todo.month == month && todo.shownInMonth == true
}
}
let descriptor = FetchDescriptor<ApproachModel>(predicate: predicate)
todos = try modelContext.fetch(descriptor)
} catch {
print("Failed to fetch month data")
}
}
func fetchYearData() {
do {
let calendar = Calendar.init(identifier: .iso8601)
let date = calendar.date(from: DateComponents(year: year, month: 1, day: 1))!
let dayOfWeek = calendar.component(.weekday, from: date)
var predicate: Predicate<ApproachModel>
if (dayOfWeek != 2) {
let previousYear = calendar.date(from: DateComponents(year: year - 1, month: 1, day: 1))!
let previousYearRange = calendar.range(of: .weekOfYear, in: .yearForWeekOfYear, for: previousYear)
predicate = #Predicate { todo in
((todo.year == year && todo.month == month) || (todo.year == year - 1 && todo.week == previousYearRange?.count)) && todo.shownInMonth == true
}
} else {
predicate = #Predicate { todo in
todo.year == year && todo.month == month && todo.shownInMonth == true
}
}
let descriptor = FetchDescriptor<ApproachModel>(predicate: predicate)
todos = try modelContext.fetch(descriptor)
} catch {
print("Failed to fetch year data")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment