@propertyWrapper
public struct PropertyWrapperString: Codable {
public var wrappedValue: String?
public init(wrappedValue: String?) {
self.wrappedValue = wrappedValue
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
var value: String?
if let temp = try? container.decode(String.self) {
value = temp
} else if let temp = try? container.decode(Int.self) {
value = String(temp)
} else if let temp = try? container.decode(Float.self) {
value = String(temp)
} else if let temp = try? container.decode(Double.self) {
value = String(temp)
} else {
value = nil
}
wrappedValue = value
}
}
/// 必須重寫,否則如果model缺省字段的時候會導(dǎo)致解碼失敗,找不到key
extension KeyedDecodingContainer {
func decode( _ type: PropertyWrapperString.Type, forKey key: Key) throws -> PropertyWrapperString {
try decodeIfPresent(type, forKey: key) ?? PropertyWrapperString(wrappedValue: nil)
}
}
/// encode 相應(yīng)字段
extension KeyedEncodingContainer {
mutating func encode(_ value: PropertyWrapperString, forKey key: Key) throws {
try encodeIfPresent(value.wrappedValue, forKey: key)
}
}
Codable 任意基礎(chǔ)數(shù)據(jù)類型處理為String
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 該項目源碼地址:https://github.com/ggb2312/JavaNotes/tree/master/...
- Redis所有的key(鍵)都是字符串。我們在談基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)時,討論的是存儲值的數(shù)據(jù)類型,主要包括常見的5種數(shù)據(jù)類...
- 「這是我參與2022首次更文挑戰(zhàn)的第11天,活動詳情查看:2022首次更文挑戰(zhàn)[https://juejin.cn...
- 「這是我參與2022首次更文挑戰(zhàn)的第12天,活動詳情查看:2022首次更文挑戰(zhàn)[https://juejin.cn...
- java lang包不需要導(dǎo)包 1、字符串字面值可以被看成字符串對象 2、字符串是常量,一旦被賦值,就不能改變 t...