iOS Swift开发中Codable枚举遇到意外值时如何设置为nil
问题原因
基于RawRepresentable的枚举默认自动生成的Codable实现,遇到不匹配的原始值时会直接抛出解码错误,不会使用你自定义的可失败init?(rawValue:)返回nil,所以当服务端返回0这类非预期值时就会触发解码失败。
解决方案
方案1:全局扩展KeyedDecodingContainer(推荐,适配所有同类枚举可选属性)
新增如下扩展,即可实现所有可选RawRepresentable类型属性解码失败时自动设为nil,无需修改原有业务代码:
extension KeyedDecodingContainer { func decodeIfPresent<T: RawRepresentable>(_ type: T.Type, forKey key: Key) throws -> T? where T.RawValue: Decodable { do { return try decode(T.self, forKey: key) } catch DecodingError.dataCorrupted { // 捕获原始值不匹配错误,返回nil return nil } catch { throw error } } }
这个扩展仅作用于可选的RawRepresentable类型属性,必选属性遇到无效值仍会正常抛出错误,符合常规业务逻辑。
方案2:自定义WebUser的解码逻辑(无全局影响)
如果不想添加全局扩展,可单独给WebUser实现自定义解码方法,手动处理每个枚举属性的解码异常:
class WebUser: Codable, Equatable { static func == (lhs: WebUser, rhs: WebUser) -> Bool { return lhs.id == rhs.id } let id: Int var mobileNumberPrivacy: CommonPrivacyOption? var emailPrivacy: CommonPrivacyOption? var dobPrivacy: CommonPrivacyOption? enum CodingKeys: String, CodingKey { case id, mobileNumberPrivacy, emailPrivacy, dobPrivacy } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(Int.self, forKey: .id) // 用try?捕获解码失败异常,自动设为nil mobileNumberPrivacy = try? container.decodeIfPresent(CommonPrivacyOption.self, forKey: .mobileNumberPrivacy) emailPrivacy = try? container.decodeIfPresent(CommonPrivacyOption.self, forKey: .emailPrivacy) dobPrivacy = try? container.decodeIfPresent(CommonPrivacyOption.self, forKey: .dobPrivacy) // 其他属性按原有逻辑解码即可 } }
这个方案不会影响其他模型的解码逻辑,仅针对当前WebUser生效。
两种方案都可以满足需求:遇到1/2/3/4之外的数值时,对应枚举属性自动设为nil,同时也兼容接口缺失字段的场景。
内容的提问来源于stack exchange,提问作者Mrugesh Tank
相关产品推荐
相关产品推荐

