有序字典的 onDelete 函数 - 无法将 'IndexSet' 类型的值转换为预期的参数类型 > Int



我有一个OrderedDictionary,我把它放入一个List中。如何使用onDelete函数从字典中删除单个元素?此时,它只打印字典的第一个元素。

struct RecipeIngredients: View {

@State var test: OrderedDictionary <String, String> = ["ab": "AC", "this will be middle": "middle", "third": "third"]


private func listContent(for keys: [String]) -> some View {
ForEach(keys, id: .self) { key in
HStack{
Text(key)
.font(.title2)
.foregroundColor(.green)
.fontWeight(.bold)      
}

}
.onDelete { indexSet in
let key = keys[indexSet.first!]
self.test.removeValue(forKey: key)
}
}

var body: some View {
List{
listContent(for: Array(test.keys)) 
}
.listStyle(SidebarListStyle())
}
}

所以最后修复了这个问题,我想我会在这里发布解决方案,以帮助任何可能有类似问题的人。

问题是在我绘制视图时,我没有调用test[key],它现在根据字典的位置工作并删除。

@State var test: OrderedDictionary <String, String> = ["ab": "AC", "this will be middle": "middle", "third": "third"]


private func listContent(for keys: [String]) -> some View {
ForEach(keys, id: .self) { key in
HStack{
Text(key)
.font(.title2)
.foregroundColor(.green)
.fontWeight(.bold)
Text(test[key]!)


}

}
.onDelete { indexSet in
let key = test.keys[indexSet.first!]
self.test.removeValue(forKey: key)
}
}

List{
self.listContent(for: Array(test.keys))                
}
.listStyle(SidebarListStyle())
}

最新更新