Reputation: 21
I am trying to compare the studentId with the array of dictionaries which has multiple studentId's. I need to get the dictionary which matches with the particular StudentID..Can any one please suggest the perfect solution. I am new to swift.
"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",
}
}
]
I have students array which is an array of dictionaries.Now I have to compare student Id with this existing array containing multiple studentID's. so when it matches with the student ID, I need to get that particular dictionary data. For example, I have studentId as "STUDENT14354678960" so I need to get the data containing related to this Id..
Upvotes: 0
Views: 1719
Reputation: 4918
You can use where with a closure:
let search = students.first { (element) -> Bool in
if let dict = element as? [String:Any] {
return dict["studentId"] == yourID
}
}
Upvotes: 2
Reputation: 285079
Use first
, it returns the first found object or nil
if let student = students.first(where: {$0["studentId"] as! String == "STUDENT123456789"}) {
print(student["firstName"])
} else {
print("not found")
}
It's highly recommended to use a custom struct or class for the student data for example
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)
}
Upvotes: 3