审查生成的订单解码器

来自 Codable
Swift 6.3.3 高级 6分钟 找出 4处问题

根据边界契约审查这段生成的订单解码代码。

解码订单:id 与 total 必须存在,日期使用 ISO 8601;coupon 缺失时为空字符串,但显式 null 必须拒绝;失败要保留诊断路径,而且绝不记录原始载荷。

swift
import Foundation

struct IncomingOrder: Decodable {
    let id: Int
    let coupon: String
    let createdAt: Date
    let totalCents: Int
    enum CodingKeys: String, CodingKey { case id, coupon, createdAt, totalCents }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = (try? values.decode(Int.self, forKey: .id)) ?? 0
        coupon = try values.decodeIfPresent(String.self, forKey: .coupon) ?? ""
        createdAt = try values.decode(Date.self, forKey: .createdAt)
        totalCents = try values.decode(Int.self, forKey: .totalCents)
    }
}

func decodeOrder(_ data: Data) -> IncomingOrder? {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601
    print("order payload:", String(decoding: data, as: UTF8.self))
    return try? decoder.decode(IncomingOrder.self, from: data)
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误