Codable 任意基礎(chǔ)數(shù)據(jù)類型處理為String

@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)
    }
}

Swift Codable 將任意類型解析為想要的類型
原文鏈接

最后編輯于
?著作權(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ù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容