gpt4 book ai didi

ios - 如何使用 "active"值为 "true"的所有详细信息过滤学生?

转载 作者:行者123 更新时间:2023-11-28 07:48:32 31 4
gpt4 key购买 nike

我想过滤所有 active 值为 true 的详细信息(学校、城市、姓名、事件)。我已经存储了关键“细节”的值(value)

let details = jsonRes[RequestResponses.Keys.details.rawValue] as? Dictionary< String, Any>

{
"details": {
"code": 235,
"school": "sp school",
"students": [
{ "name": "1student", "Active": false },
{ "name": "2student", "Active": true },
{ "name": "3student", "Active": true },
{ "name": "4student", "Active": false },
{ "name": "5student", "Active": false}
]
}
}

预期结果

    [
"details": {
"code": 235,
"school": "sp school",
"students": [
{ "name": "2student", "Active": true },
{ "name": "3student", "Active": true }
]
}
]

最佳答案

您可以使用过滤器

   if let details = jsonRes[RequestResponses.Keys.details.rawValue] as?  Dictionary< String, Any> ,
let detailDic = details["details"] as? [String:Any],
let students = detailDic["students"] as? [[String:Any]] {

let activeStudents = students.filter { (item) -> Bool in
guard let active = item["Active"] as? Bool else {return false}
return active
}
print(activeStudents)
}

或者您可以使用速记

     if let details = jsonRes[RequestResponses.Keys.details.rawValue] as?  Dictionary< String, Any> ,
let detailDic = details["details"] as? [String:Any],
let students = detailDic["students"] as? [[String:Any]] {

let activeStudents = (details["students"] as?
[[String:Any]])?.filter{ $0["Active"] as? Bool == true}
print(activeStudents)
}

关于ios - 如何使用 "active"值为 "true"的所有详细信息过滤学生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50309317/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com