将密钥与iOS swift 4

时间:2018-05-07 08:49:28

标签: ios arrays dictionary swift4

我正在尝试将studentId与具有多个studentId的字典数组进行比较。我需要获得与特定StudentID匹配的字典。任何人都可以建议完美的解决方案。我是新手。

"students" : [
    {
      "studentId" : "STUDENT123456789",
      "middleName" : "Evangeline",
      "firstName" : "Dia",
      "rollNo" : "1001",
      "studentClass" : {
        "className" : "Grade 10",
        "classId" : "CLASS123456789",
      }
    }
  {
      "studentId" : "STUDENT14354678960",
      "middleName" : "Joseph",
      "firstName" : "Parker",
      "rollNo" : "1002",
      "studentClass" : {
        "className" : "Grade 10",
        "classId" : "CLASS15468975467",
      }
    }
  ]

我有学生数组,这是一个字典数组。现在我必须将学生ID与包含多个studentID的现有数组进行比较。因此,当它与学生ID匹配时,我需要获取特定的字典数据。 例如,我有studentId为“STUDENT14354678960”,所以我需要获取包含与此Id相关的数据..

2 个答案:

答案 0 :(得分:2)

使用first,它会返回找到的第一个对象或nil

if let student = students.first(where: {$0["studentId"] as! String == "STUDENT123456789"}) {
   print(student["firstName"])
} else {
   print("not found")
}

强烈建议为学生数据使用自定义结构或类,例如

let jsonString = """
{"students" : [
{"studentId" : "STUDENT123456789", "middleName" : "Evangeline", "firstName" : "Dia", "rollNo" : "1001", "studentClass" : { "className" : "Grade 10", "classId" : "CLASS123456789"}},
{"studentId" : "STUDENT14354678960", "middleName" : "Joseph", "firstName" : "Parker", "rollNo" : "1002", "studentClass" : {"className" : "Grade 10", "classId" : "CLASS15468975467"}}
]}
"""

struct Root : Decodable {
    let students : [Student]
}

struct Student : Decodable {
    let studentId, middleName, firstName, rollNo : String
    let studentClass : StudentClass
}

struct  StudentClass : Decodable {
    let className, classId : String
}

let data = Data(jsonString.utf8)
do {
    let result = try JSONDecoder().decode(Root.self, from: data)
    let students = result.students
    if let student = students.first(where: {$0.studentId == "STUDENT123456789" }) {
        print(student)
    }
} catch {
    print(error)
}

答案 1 :(得分:1)

你可以使用封闭的地方:

let search = students.first { (element) -> Bool in
    if let dict = element as? [String:Any] {
        return dict["studentId"] == yourID
    }
}