我要筛选其活动值为真的所有详细信息(学校、城市、名称、活动)。我已经存储了“细节”键的值

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

最佳答案

您可以使用filter

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

或者你可以用shourthand
     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)
            }

09-11 20:16