如何使用“有效”值为“true”的所有详细信息过滤学生?

时间:2018-05-12 18:13:06

标签: ios swift

我想过滤其有效值为true的所有详细信息(学校,城市,名称,有效)。我存储了关键“细节”的价值

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

1 个答案:

答案 0 :(得分:0)

您可以使用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)
            }