[英]ForEach not working in SwiftUI after conforming to Identifiable protocol
我有一个符合Identifiable
协议的Message
数组,但我不断收到此错误: Generic parameter 'ID' could not be inferred
。 即使使用id: \\.self
也行不通。
这里发生了什么?
struct Message: Identifiable {
var id = UUID()
var text: String
var createdAt: Date = Date()
var senderId: String
init(dictionary: [String: Any]) {
self.text = dictionary["text"] as? String ?? ""
self.senderId = dictionary["senderId"] as? String ?? ""
}
}
@State var messages: [Message] = []
ForEach(messages) { message in
// Generic parameter 'ID' could not be inferred
}
你需要Text(message.id.uuidString)
import SwiftUI
struct Message: Identifiable {
var id = UUID()
var text: String
var createdAt: Date = Date()
var senderId: String
init(dictionary: [String: Any]) {
self.text = dictionary["text"] as? String ?? ""
self.senderId = dictionary["senderId"] as? String ?? ""
}
}
struct ContentView: View {
@State var messages: [Message] = [Message.init(dictionary: ["text":"t1","senderId":"1"]),Message.init(dictionary: ["text":"t2","senderId":"2"])]
var body: some View {
VStack {
ForEach(messages) { message in
Text(message.id.uuidString)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
编辑:
import SwiftUI
struct Message: Identifiable {
var id = UUID()
var text: String
var createdAt: Date = Date()
var senderId: String
init(dictionary: [String: Any]) {
self.text = dictionary["text"] as? String ?? ""
self.senderId = dictionary["senderId"] as? String ?? ""
}
}
struct ContentView: View {
@State var messages: [Message] = []
var body: some View {
VStack {
ForEach(messages) { message in
Text(message.id.uuidString)
}
}.onAppear() {
self.messages = [Message.init(dictionary: ["text":"t1","senderId":"1"]),Message.init(dictionary: ["text":"t2","senderId":"2"])]
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.