I have an array of Message
which conforms to the Identifiable
protocol but I keep getting this error: Generic parameter 'ID' could not be inferred
. Even with the id: \\.self
won't work.
What's going on here?
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
}
You need 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()
}
}
Edit:
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()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.