How to use Any in Codable Type

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

    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 {
        var id: T
        var name: String
    }
    
    let person1 = Person(id: 1, name: "John")
    let person2 = Person(id: "two", name: "Steve")
    

提交回复
热议问题