前言: 服務(wù)端新增枚舉類型, 客戶端數(shù)據(jù)解析失敗如何解決?
- 首先定義一個(gè)枚舉類型, 準(zhǔn)備在 model 中使用
/// 交易類型
enum TradeType: Int, CaseIterable {
/// 普通商品交易進(jìn)賬
case generalIncome = 1
/// 提現(xiàn)成功
case withdrawSuccess = 2
/// 提現(xiàn)中
case withdrawing = 5
/// 提現(xiàn)失敗
case withdrawFailed = 6
/// 匠人余額扣除
case balanceDeduction = 7
/// 卡券交易進(jìn)賬
case couponIncome = 8
/// 匠人保證金扣除
case depositDeduction = 20
/// 鎖粉訂單傭金減免
case lockFansOrderCommissionReduce = 21
}
extension TradeType: Codable {}
在 model 中使用枚舉
/// 收支明細(xì)列表項(xiàng)
struct TradingListItemModel: DJModel {
/// 記錄 ID
@Codec
var id: Int = 0
/// 操作描述
var desc: String?
/// 交易類型
var type: TradeType?
/// 操作后剩余金額
@Codec
var remainAmount: CurrencyFen = 0
/// 操作金額
var amount: String?
}
如果是上面的定義會(huì)存在一個(gè)問題, 如果后續(xù), 服務(wù)端擴(kuò)展枚舉類型, 而移動(dòng)端沒有進(jìn)行對(duì)應(yīng)的修改, 數(shù)據(jù)解析會(huì)不成功
所以接下來(lái) 我們 需要 有后備 case 的 Enum, 也就是說(shuō), 我們可以讓 TradeType 這個(gè) Enum 自動(dòng)處理未知情況。 具體需要怎么做呢
聲明一個(gè)協(xié)議,叫 CodableEnumeration:
protocol CodableEnumeration: RawRepresentable, Codable where RawValue: Codable {
static var defaultCase: Self { get }
}
通過 extension,讓協(xié)議提供默認(rèn) Decode 方法:
extension CodableEnumeration {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
let decoded = try container.decode(RawValue.self)
self = Self.init(rawValue: decoded) ?? Self.defaultCase
} catch {
self = Self.defaultCase
}
}
}
之后枚舉遵循這個(gè)協(xié)議
/// 交易類型
enum TradeType: Int, CaseIterable, CodableEnumeration {
static var defaultCase: TradeType {
.unknown
}
/// 未知
case unknown = 99
/// 普通商品交易進(jìn)賬
case generalIncome = 1
/// 提現(xiàn)成功
case withdrawSuccess = 2
之后就不怕服務(wù)端新增類型, 做到能很好的兼容數(shù)據(jù)問題 !