【问题标题】:Finding specific item and change value in model - Swift在模型中查找特定项目并更改值 - Swift
【发布时间】:2020-08-19 09:11:18
【问题描述】:

我正在尝试更改模型中的值或更新值,但由于某种未知原因,它没有更新值。 我已经通过匹配 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?
    }

【问题讨论】:

  • 为什么所有的东西都是可选的?这是你的 json 还是来自一些外部的 rest api?
  • @JoakimDanielson - 我的 Json,是的,我会设置它。

标签: ios arrays swift model codable


【解决方案1】:

假设您将数组属性更改为声明为 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"
        }
    }
}

【讨论】:

    【解决方案2】:

    因为你的模型被定义为 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"
            }
    
    

    【讨论】:

    • 我已经尝试过您的代码,但具体值仍未更新。
    • is AppDetailData?.sectionList?[index].items?[0] 是你要更改的项目???
    • 感谢您的大力支持,我做了一些小改动,现在可以正常工作了。
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2012-06-28
    相关资源
    最近更新 更多