简体   繁体   中英

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM