在Swift中根据其属性删除数组对象 [英] Removing array object according to its property in Swift
本文介绍了在Swift中根据其属性删除数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的自定义数组,我想删除学生ID为4的元素
I have a custom array like this and I want to delete the element where Student id is 4
var strNames = [Student(id: 1, name: "ghj"), Student(id: 4, name: "def"), Student(id: 9, name: "bkl")]
我确实喜欢这样.有人可以帮我用Swift方式映射吗?
In classic way I do like this. Can anybody please help me mapping in Swift way?
var sArray2: [Student] = []
for item in strNames {
if item.id != 4 {
sArray2.append(Student(id: item.id, name: item.name))
}
}
strNames = sArray2
推荐答案
您可以使用 RangeReplaceableCollection
变异方法:
mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
在您的情况下:
In your case:
strNames.removeAll { $0.id == 4 }
这篇关于在Swift中根据其属性删除数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文