Swift中可兼容Int与String类型的变量定义及API解码问题
问题根源
Swift 的 Codable 解码是严格类型匹配逻辑,默认不会自动兼容同一字段下的多类型取值,也不会做跨类型的隐式转换:
- 把字段声明为
String/String?时,遇到返回值是Int类型的 0、1,会直接抛出类型不匹配错误 - 把字段声明为
Int/Int?时,遇到返回值是字符串"skip",也会直接解码失败
这也是你之前试了所有单一基础类型都失效的核心原因。
具体解决方案
针对这个字段可能是 Int(0/1)、可能是 String("skip")的场景,需要手动实现自定义解码逻辑,两种常用实现方式如下:
方案1:用自定义枚举承载多类型取值
枚举可以通过关联值区分不同类型的返回结果,结构更清晰,后续读代码时也能明确知晓这个字段的所有可能取值。
首先定义适配该字段的可解码枚举:
enum StateValue: Decodable { // 对应返回值是0/1的Int类型场景 case numeric(Int) // 对应返回值是"skip"的字符串场景 case skipped init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() // 先尝试解码为Int值 if let intValue = try? container.decode(Int.self) { self = .numeric(intValue) return } // 再尝试解码为字符串值 if let stringValue = try? container.decode(String.self), stringValue == "skip" { self = .skipped return } // 两种类型都匹配不上时抛出明确的解码错误 throw DecodingError.typeMismatch( StateValue.self, .init(codingPath: decoder.codingPath, debugDescription: "字段取值不符合预期") ) } }
再把原结构体里的state字段类型替换成这个自定义枚举即可:
struct DatesData: Decodable { let state: StateValue let date: String? enum CodingKeys: String, CodingKey { case state case date = "dates" } }
使用的时候可以通过 switch 匹配不同取值:
switch item.state { case .numeric(let value): // 处理0/1的数字逻辑 print("状态值:\(value)") case .skipped: // 处理skip的逻辑 print("该条记录被跳过") }
方案2:统一字段类型做兼容性解码
如果不想额外引入枚举类型,想保持原有的基础类型存储,比如最终state都统一存为 String,可以直接在结构体里实现自定义解码方法:
struct DatesData: Decodable { let state: String? let date: String? enum CodingKeys: String, CodingKey { case state case date = "dates" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) // 原有date字段的解码逻辑保持不变 date = try container.decodeIfPresent(String.self, forKey: .date) // 兼容多类型的state字段解码 if let intState = try? container.decode(Int.self, forKey: .state) { // 遇到Int类型的0/1,转成字符串存储 state = String(intState) } else if let stringState = try? container.decodeIfPresent(String.self, forKey: .state) { // 遇到"skip"字符串直接存储 state = stringState } else { state = nil } } }
易踩的注意点
你提供的示例响应里写的state = skip;是不带双引号的写法,这不符合标准JSON格式要求,实际开发中需要确认接口返回的skip是带双引号的字符串值——如果真的返回不带引号的标识符,从接口层面就是无效JSON,解码会直接在解析JSON阶段失败,和字段类型定义无关。
内容的提问来源于stack exchange,提问作者testkn
相关产品推荐
相关产品推荐

