【问题标题】:ForEach not working in SwiftUI after conforming to Identifiable protocolForEach 在符合 Identifiable 协议后无法在 SwiftUI 中工作
【发布时间】:2019-12-29 16:38:50
【问题描述】:

我有一个符合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
}

【问题讨论】:

  • ForEach 不能为空,必须有视图。
  • 我已将您的 ForEach 放入 List 中,并且编译良好。使用 Xcode 11.2 测试。编译器可能会在 SwiftUI 中给出错误的位置和/或错误,因此您需要提供在哪里看到此错误的视图主体的完整代码快照。我想原因在不同的地方。

标签: swift swiftui swift5


【解决方案1】:

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

【讨论】:

  • 现在我得到Generic parameter 'S' could not be inferred
  • 我的数组稍后会在开头为空时填充数据。所以它填充了.onAppear 你可以尝试使用一个空数组然后在出现时填充它吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
相关资源
最近更新 更多