Reputation: 149
I am trying to change value or update value in model but for some unknown reason it's not updating value.
I have accurately found the row by matching id's but after that value is not updating.
I want to update bgColor
in Item
model.
Deceleration: var AppDetailData : AppointmentDetail?
My Code:
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 Model:
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?
}
Upvotes: 0
Views: 1044
Reputation: 51972
Assuming you change your array properties to be var
declared and not optional and the unitId
(all *Id properties really) to non optional you can use the following
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"
}
}
}
Upvotes: 1
Reputation: 589
Because your model is define as Struct, so to modify you must call AppDetailsData..... to change. For example: change your sectionList variable from let to var, and change your code with this
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"
}
Upvotes: 0