SwiftUI,JSON 文件中的列表仅显示第一个元素
SwiftUI, List from the JSON file shows only the first element
请帮助 JSON 了解 SwiftUI
json 文件读取并打印,但是当您创建一个列表时,它只读取第一个元素..我做错了什么???
struct ContentView: View {
var fetch = Fetch()
public var body: some View {
// Text(fetch.persons.description)
List(fetch.persons){ user in
Text(user.name)
}
}
}
List
适用于符合 Identifiable
的对象,id
用于唯一标识每个对象,这就是 List
能够跟踪插入的方式、删除和编辑。
在你的例子中,id
是 nil
,这打破了它。
相反,请确保 id
唯一标识列表中的每个对象:
struct Foo: Identifiable {
var id = UUID()
// ...
}
var foos: [Foo]
List(foos) { foo in
// ...
}
或者,您需要为 属性 提供一个 KeyPath,它可以充当唯一 ID(并且它需要符合 Hashable
),它可以是元素本身。
struct Foo: Hashable { }
var foos: [Foo]
List(foos, id: \.self) {
// ...
}
请帮助 JSON 了解 SwiftUI json 文件读取并打印,但是当您创建一个列表时,它只读取第一个元素..我做错了什么???
struct ContentView: View {
var fetch = Fetch()
public var body: some View {
// Text(fetch.persons.description)
List(fetch.persons){ user in
Text(user.name)
}
}
}
List
适用于符合 Identifiable
的对象,id
用于唯一标识每个对象,这就是 List
能够跟踪插入的方式、删除和编辑。
在你的例子中,id
是 nil
,这打破了它。
相反,请确保 id
唯一标识列表中的每个对象:
struct Foo: Identifiable {
var id = UUID()
// ...
}
var foos: [Foo]
List(foos) { foo in
// ...
}
或者,您需要为 属性 提供一个 KeyPath,它可以充当唯一 ID(并且它需要符合 Hashable
),它可以是元素本身。
struct Foo: Hashable { }
var foos: [Foo]
List(foos, id: \.self) {
// ...
}