当我使用特定的部门ID时,我想要所有的员工姓名

时间:2018-03-13 12:59:43

标签: ios arrays json swift

当我选择特定部门(名称)并使用该部门名称(获取部门ID)并使用该ID搜索所有员工数据或所有员工数据时,我使用此代码保存所有员工数据类似于部门id保存到数组并打印出来。 但是当我使用该代码时,它会打印员工ID为nil并打印所有员工姓名(所有部门ID)

API data

if let deptt = dictData["departments"] as? [Any] {

                print(deptt)

                for i in deptt as! [[String : Any]]
                {
                    let depttName = i["name"] as? String
                    let depttID = i["id"] as? String
                    //print(i["name"]!)

                    if depttName == selectedDeptt
                    {
                        let emp = dictData["employees"] as? [Any]

                        for j in emp as! [[String : Any]]
                        {
                            let empID = j["department_id"] as? String
                            let empName = j["name"] as? String

                            print("Employee ID is : \(String(describing: empID))")

                            if depttID == empID
                            {
                                print("Employee ID is : \(String(describing: empID))")
                                print("Employee Names : \(String(describing: empName))")
                                arrEmp.append(empName!)
                            }
                        }
                    }
                }

1 个答案:

答案 0 :(得分:0)

//考虑一个带密钥的字典"员工"和[员工]

类型的值
let dict = ["Employees":[Employee(deptId:"4",id: "2", name: "Naman"),Employee(deptId:"3",id: "3", name: "Ayush Agrawal"),Employee(deptId:"4",id: "5", name: "Manish")]]

//获取员工数组

let employeeArray = dict["Employees"]

// set dept id

let deptId = "4"

//根据deptId

应用过滤器
let filteredArray = employeeArray?.filter({ (emp) -> Bool in
    emp.deptId == deptId
})