首页 > 解决方案 > 在模型中查找特定项目并更改值 - Swift

问题描述

我正在尝试更改模型中的值或更新值,但由于某种未知原因,它没有更新值。我已经通过匹配 id 准确地找到了该行,但之后该值没有更新。我想更新模型bgColorItem

减速: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?
    }

标签: iosarraysswiftmodelcodable

解决方案


假设您将要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"
        }
    }
}

推荐阅读