I have an array of selectedWeekdays
and I want to append the shifts
array in the Weekday
object.
For instance, I want to append the array of shifts for every instance in selectedWeekdays
where name
is equal to Monday
struct Weekday: Identifiable {
var id: String = UUID().uuidString
var name: String
var index: Int
var shifts: [Shift]
}
struct Shift: Identifiable, Encodable {
var id: String = UUID().uuidString
var startTime: Date
var endTime: Date
}
@Published var selectedWeekdays: [Weekday] = []
I have tried the following but it does not work:
self.selectedWeekdays.contains(where: {$0.name == weekday}).shifts.append({Shift(startTime: startTime, endTime: endTime)})
It shows the following error:
Value of type 'Bool' has no member 'shifts'
CodePudding user response:
the contains
returns boolean
, and you are trying to use as the array of the Weekday itself.
To filter the array and return the same structure, you must use the filter
function and iterate with them using compactMap
(which iterates to every not null element).
self.selectedWeekdays
.filter { $0.name == weekday }
.compactMap { $0.shifts.append(
Shift(startTime: startTime, endTime: endTime)
)
}
CodePudding user response:
you can use to get the certain item, but it might require you to unwrap the optional first.
if var item = selectedWeekdays.first(where: {$0.name == weekday}) {
item.shifts.append(your new element)
}