ios - 在模型中查找特定项目并更改值 - 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"
}
}
}
推荐阅读
- javascript - OnClick 元素使用 JS 填充数组
- wordpress - ACF 不会将计算值保存到自定义分类中的自定义字段
- electron - 识别初级电子窗口
- facebook - 用于获取喜欢计数的 Facebook API
- firebase - 在使用 firebase 动态链接时,我是否需要为电子商务应用中的每个产品手动创建动态链接?
- javascript - 当我在数据表中添加按钮(打印)时,lengthChange 不显示
- dart - text justify 不能与 RichText 一起正常工作
- python - 双击将 txt 文件添加到自定义 PyQt 编辑器
- android - 预期为 BEGIN_OBJECT,但在第 1 行第 1 列路径为 STRING - Laravel 到改造 2
- php - 下单成功后更改第 n 个订单的用户角色