简体   繁体   English

ForEach 在符合 Identifiable 协议后无法在 SwiftUI 中工作

[英]ForEach not working in SwiftUI after conforming to Identifiable protocol

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 .我有一个符合Identifiable协议的Message数组,但我不断收到此错误: Generic parameter 'ID' could not be inferred Even with the id: \\.self won't work.即使使用id: \\.self也行不通。

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)你需要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()
    }
}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM