我想更新嵌套项目数组中的项目,为了展示问题,我在下面编写了示例代码,这个问题的重点是更新嵌套项目而不是 SwiftUI 技巧。我想找到一个知道其 id 的项目,找到后尝试更新。在下面的代码中,我向您展示了更新第一层项目的示例,但只要层数更深,我们就无法猜测它可以是 2 层还是 10 层,我们不知道。我怎样才能更新item1、item2和item4?
import SwiftUI
@main
struct findItem_testApp: App {
var body: some Scene {
WindowGroup {
ContentView().environmentObject(ItemModel.shared)
}
}
}
struct ContentView: View {
@EnvironmentObject var itemModel: ItemModel
var body: some View {
VStack {
MyView(item: itemModel.items[0])
MyView(item: itemModel.items[1].nestedItems[0].nestedItems[0])
MyView(item: itemModel.items[1].nestedItems[0])
MyView(item: itemModel.items[1])
MyView(item: itemModel.items[2].nestedItems[0])
MyView(item: itemModel.items[2])
}
}
}
struct MyView: View {
let item: ItemType
var body: some View {
Text(item.name)
.bold()
.padding()
.onTapGesture {
print(item.name, item.id)
// need to update item.name from model
ItemModel.shared.updateName(id: item.id, value: item.name + " updated!")
}
}
}
struct ItemType: Identifiable {
let id: UUID
var name: String
var nestedItems: [ItemType]
init(name: String, nestedItems: [ItemType]) {
self.id = UUID()
self.name = name
self.nestedItems = nestedItems
}
}
let item0: ItemType = ItemType(name: "item0", nestedItems: [])
let item1: ItemType = ItemType(name: "item1", nestedItems: [])
let item2: ItemType = ItemType(name: "item2", nestedItems: [item1])
let item3: ItemType = ItemType(name: "item3", nestedItems: [item2])
let item4: ItemType = ItemType(name: "item4", nestedItems: [])
let item5: ItemType = ItemType(name: "item5", nestedItems: [item4])
class ItemModel: ObservableObject {
static let shared: ItemModel = ItemModel()
@Published var items: [ItemType] = [ItemType]()
init() {
self.items = [item0, item3, item5]
}
func updateName(id: UUID, value: String) {
for i in (0 ..< self.items.count) {
if (self.items[i].id == id) {
self.items[i].name = value
break
}
}
}
}
采用递归方法怎么样:
如果你想使用字典而不是数组
nestedItems
:示例输出: