Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an element from array of object on swift based on id? [closed]

Tags:

arrays

swift

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.

like image 988
TechChain Avatar asked Nov 16 '25 07:11

TechChain


1 Answers

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)
            }
        }
    }
like image 126
Iraniya Naynesh Avatar answered Nov 17 '25 21:11

Iraniya Naynesh