Home > OS >  Remove Object From Array with Specific Requirement
Remove Object From Array with Specific Requirement

Time:08-09

I have a custom object Shift

struct Shift: Identifiable, Encodable, Equatable {
    var id: String = UUID().uuidString
    var weekday: String
    var startTime: Date
    var endTime: Date
}

And an array of Shift objects:

@Published var shifts: [Shift] = []

I would like to remove the last item in the array where the value of weekday is equal to "Monday"

I tried this but it throws an error saying Value of type 'Array<Shift>.Index' (aka 'Int') has no member 'removeLast'

if let index = shifts.firstIndex(where: {$0.weekday == "Monday"}) {
    index.removeLast()
}

Any help is appreciated :)

CodePudding user response:

No, you want the last index and you want to remove the item from the shifts array rather than from the index

if let index = shifts.lastIndex(where: {$0.weekday == "Monday"}) {
    shifts.remove(at: index)
}
  • Related