0

I have a NSObject class look like this:

class MyItem : NSObject {

    var id: Int
    var name: String

    //other init code here
 }

So the array I define like this

var myItem = [MyItem]()

Here is the sample of my array:

{
"id" : 2
"name" : "Ali"

"id" : 3
"name" : "janice"

"id" : 2
"name" : "Ali"

"id" : 5
"name" : "tupac"

"id" : 2
"name" : "Ali"

"id" : 8
"name" : "William"

"id" : 2
"name" : "Ali"  
}

What I want to do is,write a function to remove all the element with the id which is equal to 2,so the array just left the element with id equal to [3,5,8].

I tried this code,but it just remove 1 element only but I want to remove all four element with id = 2

func removeId(id : Int){
  //find the index 1st
   guard let foundIndex = myItem.index(where: { $0.id == id }) else { return }
   myItem.remove(at: foundIndex)
}

Somebody please help,Thank you

2 Answers 2

1

Use filter:

func removeId(id: Int) {
   myItem = myItem.filter { $0.id != id }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use filter() predicate to filter your array as show below

var myArray = ["Hello","Coding","World"]

myArray = myArray.filter{$0 != "Hello"}

print(myArray)   // "[Coding, World]"

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.