How to use Any in Codable Type

后端 未结 11 773
猫巷女王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:05

    Thanks to Luka Angeletti's answer (https://stackoverflow.com/a/48388443/7057338) i've changed enum to struct so we can use it more easily

    struct QuantumValue: Codable {
    
        public var string: String?
        public var integer: Int?
    
        init(from decoder: Decoder) throws {
            let container = try decoder.singleValueContainer()
            if let int = try? container.decode(Int.self) {
                self.integer = int
                return
            }
            if let string = try? container.decode(String.self) {
                self.string = string
                return
            }
            throw QuantumError.missingValue
        }
    
        func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()
            try container.encode(string)
            try container.encode(integer)
        }
    
        enum QuantumError: Error {
             case missingValue
        }
    
        func value() -> Any? {
            if let s = string {
                return s
            }
            if let i = integer {
                return i
            }
            return nil
        }
    }
    

提交回复
热议问题