I have a array of objects such as.
var arrStudents = [S1,S2,S3,S4,S5]
Here s1 is object of student class
class Student {
var id:Int!
var name:String!
var address:String?
var phone:Int!
}
Now I want to delete a record from array by the the student id. please tell me how can I do this.
loop through all the indexes of the array and check if the id you want to delete matches, if yes it will filter out and you can remove that index :-)
let idToDelete = 10
if let index = arrStudents.index(where: {$0.id == idToDelete}) {
array.remove(at: index)
}
if you want to remove multiple value in single iteration you should start the loop from last index to first index, so it will not crash (out of bound error )
var idsToDelete = [10, 20]
for id in idsToDelete {
for (i,str) in arrStudents.enumerated().reversed()
{
if str.id == id
{
arrStudents.remove(at: i)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With