循环浏览任意NSDictionary数组以生成列表



我正在进行一个Swift项目,需要在列表中显示一组字典。我无法使格式在不断运行时遇到随机错误,就像它不期望出现[NSDictionary]类型的绑定错误一样。

我的数组是这样的:

items = [{"name": "jack"}, {"name" : "joe"}, {"name" : "john"}]

其中,每个字典都是一个NSDictionary。我试着做一些List{ ForEach()},但也不起作用。我觉得这种数据设置很常见,通过字典列表来完成列表应该不会太难。

List(items) {item in
Text(items.name)
}

像这样简单的事情我在其他地方看到过,但给了我一个错误:

Cannot convert value of type '[NSDictionary]' to expected argument type 'Binding<Data>'
Generic parameter 'Data' could not be inferred
Initializer 'init(_:)' requires that 'Binding<Subject>' conform to 'StringProtocol'

这不是打字错误吗?它应该是item.name而不是items.name。Items是列表本身,假设您通过item对象到达UI。

List(items) {item in
Text(item.name)
}

您可以尝试这种方法,如SwiftUI中的示例代码所示。由于您需要一个字典数组,因此需要2个ForEach循环,一个在字典数组上,一个在特定字典的键上。

请注意,如果使用Dictionary而不是NSDictionary,则会稍微简单一些。

struct ContentView: View {
@State var items: [NSDictionary] = [["name" : "jack"], ["name" : "joe"], ["name" : "john"]] 

var body: some View {
List {
ForEach(items, id: .self) { item in  // <-- loop over the dictionaries
ForEach(item.allKeys as! [String], id: .self) { key in // <-- loop over dictionary keys
Text(item[key] as? String ?? "")
}
}
}
}
}

如果你只将"name"作为字典中的唯一密钥,那么你可以使用这个:

List {
ForEach(items, id: .self) { item in
Text(item["name"] as? String ?? "")
}
}

另一种方法,如果您只有name作为密钥:

struct ContentView: View {
@State var items: [NSDictionary] = [["name" : "jack"], ["name" : "joe"], ["name" : "john"]]

var body: some View {
List(items.compactMap{ ($0.allValues.first as? String)}, id: .self) { name in
Text(name)
}
}
}

使用Dictionary,如[String:String]:

struct ContentView: View {
@State var items = [["name" : "jack"], ["name" : "joe"], ["name" : "john"]]

var body: some View {
List(items, id: .self) { item in
Text(item["name"] ?? "")
}
}
}

最新更新