0

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 :)

1
  • You need a forEach for each workingHours and a forEach for each Shift in availability`. A nested loop, you will find help if you search that term. Commented Apr 27, 2022 at 14:51

2 Answers 2

2

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" } }
Sign up to request clarification or add additional context in comments.

1 Comment

@devOP1, this answer is incorrect since it will remove all instances of WorkingHours that contains a Shift for Monday rather than removing only the Shift object that has weekDay == "Monday"
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.