首页 > 解决方案 > 无法使用 UUID() 解析 Json 名称

问题描述

我有下一个解析模型

struct Unicards: Hashable, Codable, Identifiable {
var id: String?
var title: String?
var info: String?
var brand: String?
var model: String?
var make_year: Int?
var message: String?
var message_color: String?

我有一个 Json 文件,其中有许多具有不同数据集的重复数组,但具有相同的标头,有时是重复的 ID

我想用

var uuid = UUID() 

为每个数据集生成唯一 ID 并使用唯一 ID 功能

list (model, id: \ .uuid)

但是当我添加这一行时,我得到一个错误

   "Thread 1: Fatal error: Couldn't parse" Json name ""

我犯了什么错误,请告诉我

我已经浏览了很多答案,但我不明白我的错误到底是什么。

试过了

var uuid: UUID = UUID ()

var uuid = UUID (). uuidString

标签: modeluuidswiftuicodableswift5

解决方案


您的错误的原因是,通过确认Codable协议,它会尝试合成值,并且当您添加一个不存在的值时,解码器会感到困惑。要解决这个问题,您需要做的就是CodingKeys在您的结构中添加一个枚举。

struct Unicards: Hashable, Codable, Identifiable {

    var uuid: UUID = UUID()

    var id: String?
    var title: String?
    var info: String?
    var brand: String?
    var model: String?
    var make_year: Int?           // by convention this should be makeYear
    var message: String?
    var message_color: String?    // by convention this should be messageColor

    enum CodingKeys: String, CodingKey {
        case id
        case title
        case info
        case brand
        case model
        case message
        case make_year
        case message_color

        // if you use the usual naming convention, you could swap these out
        // case makeYear = "make_year",
        // case messageColor = "message_color"
    }

}

推荐阅读