Codable 任意基础数据类型处理为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缺省字段的时候会导致解码失败,找不到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)