I’m having trouble displaying the day from a date. I have multiple dates in the format "2022-12-27T04:00:31.980". I want the "Picker" to be able to select the date after the day of the month. The problem arises when I have the same date but different time, because "Picker" shows me the day as many times as it appears with a different time.
This is my "Picker" code:
Picker(selection: $currentTab, label: Text("Wybierz dzień")) {
let calendar = Calendar.current
ForEach(temperatureCall.chartDataEntries) { item in
let components = calendar.dateComponents([.day, .month, .year], from: item.lastupdated)
let day = components.day!
let month = components.month!
let year = components.year!
Text("(String(day)).(String(month)).(String(year))")
.tag(String(day))
}
}
I would like each day to be unique and to be able to choose a day no matter how many times it is repeated with a different time.
let calendar = Calendar.current
let dates = Set(temperatureCall.chartDataEntries.map { calendar.startOfDay(for: $0.lastupdated) })
Picker(selection: $currentTab, label: Text("Wybierz dzień")) {
ForEach(dates) { item in
let components = calendar.dateComponents([.day, .month, .year], from: item)
let day = components.day!
let month = components.month!
let year = components.year!
Text("(String(day)).(String(month)).(String(year))")
.tag(String(day))
}
}
I did something like this, unfortunately I get an error:
Cannot convert value of type 'Set<Date>' to expected argument type 'Binding<C>'
3
Answers
I would map to start of day and use
Set
to get unique valuesThis could be done as a computed property in temperatureCall and then you can use this property in your
ForEach
insteadAnother option is to use
OrderedSet
from the Swift Collections package which will not only keep only the unique values but also maintain the original order of the input arrayStarting from @JoakimDanielson answer, code that preserves the original order and has ≈
O(1)
performance would look something like this (It could be made shorter. I left it verbose for ease of reading.)Here is some working test code using the above, as a command line tool. (I wrote the test code to generate dates in random order so you can tell that the uniqueDates code preserves the original order of the array.)
Note that calculating unique dates would take a non-trivial amount of time for a large array of dates, so using a computed property isn’t the best way to do this. It would be better to compute the unique dates the first time you ask for it after the source array of dates changes.
A test run of that outputs: