我的NSObject
课程看起来像这样:
class MyItem : NSObject {
var id: Int
var name: String
//other init code here
}
所以我这样定义的数组
var myItem = [MyItem]()
以下是我的数据示例:
{
"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"
}
我想要做的是,编写一个函数来移除id
等于2
的所有元素,所以数组刚离开元素id
等于[3,5,8]
。
我尝试了这段代码,但它只删除了1个元素,但我想删除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)
}
有人请帮忙,谢谢
答案 0 :(得分:1)
使用filter
:
func removeId(id: Int) {
myItem = myItem.filter { $0.id != id }
}
答案 1 :(得分:1)
您可以使用filter()谓词过滤数组,如下所示
var myArray = ["Hello","Coding","World"]
myArray = myArray.filter{$0 != "Hello"}
print(myArray) // "[Coding, World]"