Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove Object From Array with Specific Requirement

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading