You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5 Codable适配API动态字段:example字段时有时无

解决Codable处理可选字段的问题

你的问题出在example字段被定义为非可选的String类型,当API返回的数据不包含这个字段时,Codable会解码失败。只需要把example改为可选类型,或者自定义解码逻辑来处理缺失的情况。

方案1:将example设为可选类型

这是最简单的方式,当API不返回example时,该字段会被自动设为nil:

struct Definition: Codable {
    var definition: String
    var synonyms: [String]
    var antonyms: [String]
    var example: String? // 修改为可选类型

    enum CodingKeys: String, CodingKey {
        case definition
        case synonyms
        case antonyms
        case example
    }
}

方案2:给example设置默认值(比如空字符串)

如果不想让example为nil,希望缺失时用默认值填充,可以自定义解码初始化方法:

struct Definition: Codable {
    var definition: String
    var synonyms: [String]
    var antonyms: [String]
    var example: String

    enum CodingKeys: String, CodingKey {
        case definition
        case synonyms
        case antonyms
        case example
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        definition = try container.decode(String.self, forKey: .definition)
        synonyms = try container.decode([String].self, forKey: .synonyms)
        antonyms = try container.decode([String].self, forKey: .antonyms)
        // 使用decodeIfPresent,缺失时返回默认值空字符串
        example = try container.decodeIfPresent(String.self, forKey: .example) ?? ""
    }
}

注意:你原来的结构体名拼写是Defination,建议修正为标准的Definition(少了一个i),避免后续代码出现命名混淆。

内容的提问来源于stack exchange,提问作者RUPESH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 12:06:28