How to use Any in Codable Type

后端 未结 11 766
猫巷女王i
猫巷女王i 2020-11-29 04:20

I\'m currently working with Codable types in my project and facing an issue.

struct Person: Codable
{
    var id: Any
}

11条回答
  •  情书的邮戳
    2020-11-29 05:21

    To make key as Any, I like all above answers. But when you are not sure which data type your server guy will send then you use Quantum class (as above), But Quantum type is little difficult to use or manage. So here is my solution to make your decodable class key as a Any data type (or "id" for obj-c lovers)

       class StatusResp:Decodable{
        var success:Id? // Here i am not sure which datatype my server guy will send
    }
    enum Id: Decodable {
    
        case int(Int), double(Double), string(String) // Add more cases if you want
    
        init(from decoder: Decoder) throws {
    
            //Check each case
            if let dbl = try? decoder.singleValueContainer().decode(Double.self),dbl.truncatingRemainder(dividingBy: 1) != 0  { // It is double not a int value
                self = .double(dbl)
                return
            }
    
            if let int = try? decoder.singleValueContainer().decode(Int.self) {
                self = .int(int)
                return
            }
            if let string = try? decoder.singleValueContainer().decode(String.self) {
                self = .string(string)
                return
            }
            throw IdError.missingValue
        }
    
        enum IdError:Error { // If no case matched
            case missingValue
        }
    
        var any:Any{
            get{
                switch self {
                case .double(let value):
                    return value
                case .int(let value):
                    return value
                case .string(let value):
                    return value
                }
            }
        }
    }
    

    Usage :

    let json = "{\"success\":\"hii\"}".data(using: .utf8) // response will be String
            //let json = "{\"success\":50.55}".data(using: .utf8)  //response will be Double
            //let json = "{\"success\":50}".data(using: .utf8) //response will be Int
            let decoded = try? JSONDecoder().decode(StatusResp.self, from: json!)
            print(decoded?.success) // It will print Any
    
            if let doubleValue = decoded?.success as? Double {
    
            }else if let doubleValue = decoded?.success as? Int {
    
            }else if let doubleValue = decoded?.success as? String {
    
            }
    

提交回复
热议问题