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
相关产品推荐
相关产品推荐

