【问题标题】:Update JSON Array in Swift 5在 Swift 5 中更新 JSON 数组
【发布时间】:2021-04-03 00:59:09
【问题描述】:

我有一个从 url 获取并使用 SwiftyJSON 转换的 JSON 数组。现在我想为某些功能更新一些 JSON 数组的值。

我的 JSON 是这样的

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

经过一些操作后,我想通过过滤 id 来更新我的 JSON 数组。 就像如果我有 id = 48845152 然后只更新

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

最后与我的 JSON 数组合并。所以最终的结果应该是

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

  ]

我的代码是这样的。

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

self.studentList 是我的 JSON。但我收到错误提示

不能通过下标赋值:'$0' 是不可变的

请有人帮我找出这里出了什么问题。

【问题讨论】:

  • $0["isAttendedToday"] = true,此行导致问题

标签: ios json swift swift5 swifty-json


【解决方案1】:

使用此语法,您无法修改源数组,但可以修改目标数组

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
    }
}

如果要修改源数组,则必须使用它

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

在这两种情况下,由于值类型语义,您必须直接修改数组。

PS:

在 Swift 5 中,没有理由再使用 SwiftyJSONCodable 更通用、更高效且内置。

【讨论】:

  • 您的第一个解决方案出现了一些错误,提示“无法分配给属性:'last' 是一个只能获取的属性”。但是第二种方法是有效的。谢谢
  • 请查看编辑并注意这两个建议做不同的事情。
  • 非常感谢,但您能描述一下为什么会出现“无法通过下标赋值:'$0' 是不可变的”错误吗??
  • $0 表示循环中的当前项。它是一个副本并被视为let 常量,因此是不可变的。
  • 再次感谢。其实我是新来的 swift 和学习工作
猜你喜欢
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多