iosswiftcodabledecodableencodable

How to use Any in Codable Type


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

struct Person: Codable
{
    var id: Any
}

id in the above code could be either a String or an Int. This is the reason id is of type Any.

I know that Any is not Codable.

What I need to know is how can I make it work.


Solution

  • Codable needs to know the type to cast to.

    Firstly I would try to address the issue of not knowing the type, see if you can fix that and make it simpler.

    Otherwise the only way I can think of solving your issue currently is to use generics like below.

    struct Person<T> {
        var id: T
        var name: String
    }
    
    let person1 = Person<Int>(id: 1, name: "John")
    let person2 = Person<String>(id: "two", name: "Steve")