[英]Get array of particular property of model obj based on condition Swift
I have a model as follows: 我有一个模型如下:
class Expertise:NSObject{
var expertise:String = ""
var isSelevted:Bool = false
}
I want the array of the selected expertise. 我想要一系列精选的专业知识。
I tried: 我试过了:
Obj.filter{$0.isSelected == true}.first.expertise
but the above line didn't worked. 但是上面的行不起作用。
要获取数组中每个选定对象的专业知识值,请使用过滤器和映射:
objects.filter { $0.isSelected } .map { $0.expertise }
You are returning the first selected expertise. 您将返回首选的专业知识。 To get the array of the selected expertise just use this
要获得一系列选定的专业知识,只需使用此
let selectedExpertises = Obj.filter{$0.isSelected == true}
Then you can get the expertises names like this 然后,您可以获得这样的专业名称
for expertise in selectedExpertises {
print(expertise.expertise)
}
Update: to get the array of expertises names : 更新:获取一系列专业名称:
var expertises: [String] = []
let selectedExpertises = Obj.filter{$0.isSelected == true}
for expertise in selectedExpertises {
expertises.append(expertise.expertise)
}
Another way: 其他方式:
var expertises: [String] = []
for expertise in Obj {
if expertise.isSelected {
expertises.append(expertise.expertise)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.