美文网首页
Codable 任意基础数据类型处理为String

Codable 任意基础数据类型处理为String

作者: _风雨 | 来源:发表于2022-03-01 17:35 被阅读0次
    @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缺省字段的时候会导致解码失败,找不到key
    extension KeyedDecodingContainer {
        func decode( _ type: PropertyWrapperString.Type, forKey key: Key) throws -> PropertyWrapperString {
            try decodeIfPresent(type, forKey: key) ?? PropertyWrapperString(wrappedValue: nil)
        }
    }
    
    /// encode 相应字段
    extension KeyedEncodingContainer {
        mutating func encode(_ value: PropertyWrapperString, forKey key: Key) throws {
            try encodeIfPresent(value.wrappedValue, forKey: key)
        }
    }
    

    Swift Codable 将任意类型解析为想要的类型
    原文链接

    相关文章

      网友评论

          本文标题:Codable 任意基础数据类型处理为String

          本文链接:https://www.haomeiwen.com/subject/hsfjrrtx.html