我试图更改或更新模型中的值,但由于某种未知原因,它没有更新值。我已经通过匹配id准确地找到了行,但在该值之后不会更新。我想更新Item
模型中的bgColor
。
减速:var AppDetailData : AppointmentDetail?
我的代码:
for var i in AppDetailData?.sectionList ?? [] {
for j in i.items ?? [] {
if let row = i.items?.firstIndex(where: {$0.unitId == id}) {
i.items?[row].bgColor = "yellow"
}
}
}
JSON模型:
struct AppointmentDetail : Codable {
let projectId : Int?
let projectName : String?
let projectNo : String?
let projectType : String?
let sectionList : [SectionList]?
}
struct SectionList : Codable {
let title : String?
var sectionId: Int?
var items : [Item]?
}
struct Item : Codable {
var bgColor : String?
var unitId : Int?
var latitude : Double?
var longitude : Double?
}
假设您将数组属性更改为声明的var
而非可选,并将unitId
(实际上是所有*Id属性(更改为非可选,则可以使用以下
for (index, appointment) in appointments.enumerated() {
for (index1, section) in appointment.sectionList.enumerated() {
if let index2 = section.items.firstIndex(where: {$0.unitId == id}) {
appointments[index].sectionList[index1].items[index2].bgColor = "yellow"
}
}
}
因为您的模型被定义为Struct,所以要修改,您必须调用AppDetailsData。。。。。改变。例如:将sectionList变量从let更改为var,并使用此更改代码
guard let list = AppDetailData?.sectionList else {
return
}
if let index = list.firstIndex(where: {$0.items?.first?.unitId == 1}) {
AppDetailData?.sectionList?[index].items?[0].bgColor = "yeallow"
}