符合可识别协议后,ForEach无法在SwiftUI中工作

时间:2019-12-29 16:38:50

标签: swift swiftui swift5

我有一个符合Linkify.addLinks(txtViewHolder.getTxtChatReceiver(), Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS);协议的Message数组,但是我不断收到此错误:Identifiable。即使使用Generic parameter 'ID' could not be inferred也不起作用。

这是怎么回事?

id: \.self

1 个答案:

答案 0 :(得分:0)

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

enter image description here