查找特定项目并更改模型中的值-Swift

问题描述

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...