hi,
if you just want the persons collected by month, from 1 through 12, use a dictionary and then rearrange its values (each value has type [Person]
) by key into an array (which will have type [[Person]]
. For example:
func personsByMonth() -> [[Person]] {
guard !persons.isEmpty else { return [] }
let dictionaryByMonth = Dictionary(grouping: persons, by: { $0.month })
let months = Array(1...12) // rotate this array if you want to go from October to September
return months.compactMap({ dictionaryByMonth[$0] })
}
the code above assumes that Person has a computed property month
, an integer from 1 to 12, which you can compute from the DOB using its DateComponents. the compactMap
operator is needed because some keys will not exist in the dictionary; only non-empty arrays of people by month will be returned as a result.
now you can display them in a grouped list:
List {
ForEach(personsByMonth(), id: \.self) { personsInMonth in
Section(header: Text(headerText(for: personsInMonth))) {
ForEach(personsInMonth) { person in
Text(person.name)
} // end of ForEach
} // end of Section
} // end of ForEach
} // end of List
to figure out an appropriate headerText(for: personsInMonth)
function, just recognize that all persons in personsInMonth
share the same birthday month; so just read the month of any one of them, e.g., personsInMonth[0].month
.
hope that helps,
DMG