Hi guys,
I'm losing my mind a bit trying to figure out how to create some sections based on the day component of a day but no luck. I have tried multiple methods but I'm getting stuck every time, I would appreciate any hint. Last time I tried with a dictionary and I realise that the flaw lies in the Date proprety having such a granularity that every moment is different from the other but I can't think of anything else. Thank you!
Struct:
struct Scan: Identifiable, Codable, Comparable {
var id = UUID()
var scanDate = Date()
let content: String
static func < (lhs: Scan, rhs: Scan) -> Bool {
return lhs.scanDate < rhs.scanDate
}
}
View:
struct History: View {
@EnvironmentObject var modelData: ModelData
var groupedByDate: [Date: [Scan]] {
Dictionary(grouping: modelData.scans, by: {$0.scanDate})
}
var headers: [Date] {
groupedByDate.map({ $0.key }).sorted()
}
var body: some View {
List {
ForEach(headers, id: \.self) { header in
Section(header: Text(header, style: .date)) {
ForEach(groupedByDate[header]!) { scan in
Text(scan.content)
}
}
}
}
}
Screenshot with the result :(
https://postimg.cc/0KjChTHT
edit, I tried with scanDate as a computed proprety as well but it changes the value to all my previous saved object also :(
struct Scan: Identifiable, Codable, Comparable {
var id = UUID()
var scanDate: Date {
let now = Date()
let components = Calendar.current.dateComponents([.year, .month, .day], from: now)
let date = Calendar.current.date(from: components)
return date!
}
let content: String
static func < (lhs: Scan, rhs: Scan) -> Bool {
return lhs.scanDate < rhs.scanDate
}
}
Edit2: Solved it by refering to another proprety outside the computed proprety like this:
struct Scan: Identifiable, Codable, Comparable {
var id = UUID()
var now = Date()
var scanDate: Date {
let components = Calendar.current.dateComponents([.year, .month, .day], from: now)
let date = Calendar.current.date(from: components)
return date ?? Date()
}
let content: String
static func < (lhs: Scan, rhs: Scan) -> Bool {
return lhs.scanDate < rhs.scanDate
}
}