How to encode, decode enum with unknown associated value

enum Verification {
    case single(SingleVerification)
    case multiple(MultiVerification)
    case custome(Any)
}

extension Verification {
    enum CodingKeys: CodingKey {
        case single
        case multiple
        case custome
    }
}

extension Verification: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        
        switch self {
        case .single(let alue):
            try container.encode(value, forKey: .single)
        case .multiple(let value):
            try container.encode(value, forKey: .multiple)
        case .custome(let value):
            try container.encode(value, forKey: .custome)
        }
    }
}

extension Verification: Decodable {
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let key = container.allKeys.first
        
        switch key {
        case .single:
           let value = try container.decode(SingleVerification.self, forKey: .single)
           self = .single(value)
        case .multiple:
            let value = try container.decode(MultiVerification.self, forKey: .multiple)
            self = .multiple(value)
        case .custome(let connection):
             //How 
        }
    }
}

That's really a question to you: how do you expect a value you know nothing about to be reasonably encoded?

You can try performing a cast into Encodable, like this:

if let encodableConnection = connection as? Encodable {
    try container.encode(encodableConnection, forKey: .custom)
}

but that will not help you encode values that can't be cast into Encodable or really decode anything at all, since you don't know into what type it would need to be decoded, unless you encode the type information itself too.

1 Like
case custome(Any)

I add Any to it, but the idea is how a save an unknown type like a generic codable object

Terms of Service

Privacy Policy

Cookie Policy