nikko
nikko

Reputation: 3

Swift loop through array of dictionaries and create a new one

I'm struggling on getting a new array of dictionaries with conditioned 10 elements out of 80.

here is sample of students json:

{
    "id": 111,
    "name": "John",
    "gender": "male",
    "grade": 80,
    "extraCredit": 20
},
{
    "id": 112,
    "name": "Jenny",
    "gender": "female",
    "grade": 85,
    "extraCredit": 5
}

and my struct:

struct StudentData: Decodable {
  var id: Int
  var name: String
  var grade: Int
  var extraCredit: Int
}

I need to calculate each student's grade to get final grade and display top 10 here is my code to loop through:

var newStudentData = [Dictionary<String, Any>]()
for student in studentData {
  let finalGrade = student.grade + (student.extraCredit * 0.5)
  if finalGrade > 88 {
     newStudentData.append(student)   // error on cannot convert value type of ’StudentData’ to expected argument type ‘[String: Any]
  }
}

what did I do wrong? or is there a better way?

Upvotes: 0

Views: 114

Answers (1)

Gereon
Gereon

Reputation: 17844

newStudentData is a dictionary (why?), but you're appending instances of StudentData to it. This won't work.

That said, I would probably rewrite this like so:

struct StudentData: Decodable {
    let id: Int
    let name: String
    let grade: Int
    let extraCredit: Int

    var finalGrade: Int {
        return self.grade + self.extraCredit / 2
    }
}

var students = [StudentData]()
// fill students array here

let beat88 = students.filter { $0.finalGrade > 88 }
let top10 = beat88.sorted { $0.finalGrade > $1.finalGrade }.prefix(10)

Upvotes: 1

Related Questions