Home > OS >  How to append an array inside an array?
How to append an array inside an array?

Time:04-28

I have an array of working hours, and within that array, there is another array of shifts. I would like to remove all instances in the shifts array where weekday is equal to "Monday"

struct Shift {
    let id: String = UUID().uuidString
    var weekday: String
    var startTime: String
    var endTime: String
    var error: Bool
}

struct WorkingHours: Identifiable {
    let id: String = UUID().uuidString
    var availability: [Shift]
}

class AvailabilityManager: ObservableObject {

    @Published var workingHours: [WorkingHours] = []
    
}

In my view:

@EnvironmentObject var availabilityManager: AvailabilityManager

self.availabilityManager.workingHours.removeAll(where: {$0.availability.weekday == "Monday"})

However, it says: "Value of type '[Shift]' has no member 'weekday'"

Any help is appreciated :)

CodePudding user response:

Change

self.availabilityManager.workingHours.removeAll(where: {$0.availability.weekday == "Monday"})

To

self.availabilityManager.workingHours.removeAll(where: {$0.availability.contains(where: {$0.weekday == "Monday"})})

More shorthand method

self.availabilityManager.workingHours.removeAll { $0.availability.contains { $0.weekday == "Monday" } }

CodePudding user response:

Add the following function to WorkingHours

mutating func removeShift(weekDay: String) {
    availability = availability.filter { $0.weekday != weekDay }
}

and call it like

workingHour.removeShift(weekDay: "Monday")

If you have an array of WorkinHours you can call the method using map for instance

workingHoursArray = workingHoursArray.map {
    var workingHours = $0
    workingHours.removeShift(weekDay: "Monday")
    return workingHours
}
  • Related