如何在Codable类型中使用Any [英] How to use Any in Codable Type

查看:538
本文介绍了如何在Codable类型中使用Any的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用项目中的 Codable 类型并遇到问题。

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

struct Person: Codable
{
    var id: Any
}


上面代码中的

id 可以是 String 内部。这就是 id 类型任何的原因。

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

我知道任何不是 Codable

我需要知道的是如何让它工作。

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

推荐答案

Codable需要知道要转换的类型。

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")

这篇关于如何在Codable类型中使用Any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆