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

问题描述

a simple project at 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?
}

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

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

error 1

根据我的后端应用的设计,字段 uid一个唯一编号。

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

error 2

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

解决方法

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

如果您想使用 uid 作为 id 属性,请按如下方式实现:

var id: Int { uid }