iosjsonswiftswift5swifty-json

Update JSON Array in Swift 5


I have a JSON array fetching from url and convert using SwiftyJSON. Now i want to update some value of JSON Array for some functionality.

My JSON is like

[
    {
      "id" : 48845152,
      "studentPhotoTakenCount" : 0,
      "updatedAt" : null,
      "isAttendedToday: false
    },
 {     "id" : 48845153,
      "studentPhotoTakenCount" : 0,
      "updatedAt" : null,
      "isAttendedToday: false
    },
  
  ]

After some action i want to update my JSON Array by filtering id. Like if i have id = 48845152 then only update

{
      "id" : 48845152,
      "studentPhotoTakenCount" : 0,
      "updatedAt" : null,
      "isAttendedToday: false
    }

and finally merge with my JSON Array. So the final result should be

[
    {
      "id" : 48845152,
      "studentPhotoTakenCount" : 0,
      "updatedAt" : null,
      "isAttendedToday: false
    },
 {     "id" : 48845153,
      "studentPhotoTakenCount" : 0,
      "updatedAt" : null,
      "isAttendedToday: false
    },

  ]

My code is like that.

self.studentList.forEach {
                        if let id = $0["id"].int {
                            if id == _studentId {
                                $0["isAttendedToday"] =  true
                                self.filteredStudentList.append($0)
                            }
                            else {
                                self.filteredStudentList.append($0)
                            }
                        }
                    }

Here self.studentList is my JSON. But i get the error saying that

Cannot assign through subscript: '$0' is immutable

Please someOne help me to find out what getting wrong here.


Solution

  • With this syntax you cannot modify the source array, but you could modify the destination array

    self.studentList.forEach {
        self.filteredStudentList.append($0)
        if let id = $0["id"].int, id == _studentId {
           let lastIndex = self.filteredStudentList.count - 1
           self.filteredStudentList[lastIndex]["isAttendedToday"] = true
        }
    }
    

    If the source array is supposed to be modified you have to use this

    for (index, item) in self.studentList.enumerated() {
        self.filteredStudentList.append(item)
        if let id = item["id"].int, id == _studentId {
           self.studentList[index]["isAttendedToday"] = true
        }
    }
    

    In both cases due to value type semantics you have to modify the arrays directly.

    PS:

    In Swift 5 there is no reason anymore to use SwiftyJSON. Codable is more versatile, more efficient and built-in.