如何使我的结构可识别?它有一个唯一的数字 uid 字段

Ale*_*ber 8 swift decodable swiftui swiftui-list identifiable

Github 的一个简单项目中,我尝试下载 JSON 对象列表:

struct TopResponse: Codable {
    let data: [Top]
}

struct Top: Codable /*, Identifiable */ {
    let uid: Int
    let elo: Int
    let given: String
    let photo: String?
    let motto: String?
    let avg_score: Double?
    let avg_time: String?
}
Run Code Online (Sandbox Code Playgroud)

这效果很好,下一步我想将它显示在 SwiftUI 列表中,从而添加Identifiable到结构中。

不幸的是,这会产生编译错误Type 'Top' does not conform to protocol 'Identifiable'

错误1

根据我的后端应用程序的设计,该字段uid是一个唯一的数字。

所以我试图通过将其类型从Intto更改来修复编译错误ObjectIdentifier,但 Swift 编译器仍然对新错误不满意Type 'Top' does not conform to protocol 'Decodable'

错误2

这里发生了什么,编译器现在可能缺少uid用于解码 JSON 的字段吗?(它怎么可能知道传入的服务器数据有这样的字段?)

Emi*_*aez 18

Identifiable要求您的结构具有一个id属性,它不会自动找到最适合的属性。

如果你想用作uid属性id,请像这样实现:

var id: Int { uid }
Run Code Online (Sandbox Code Playgroud)