创建具有通用类型的可编码结构 [英] Create codable struct with generic type

查看:62
本文介绍了创建具有通用类型的可编码结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,很抱歉问题标题不清楚

First of all, Sorry for unclear title of question

我正在制作一个可编码的结构,它将用作json消息。

I'm making a codable struct which will be used as json message.

enum MessageType: String, Codable{
    case content
    case request
    case response
}

struct Message: Codable{
    var type: MessageType
    var content: /* NEED HELP HERE */
}

struct Content: Codable {...}
struct Request: Codable {...}
struct Response: Codable {...}

声明消息时,如果其类型内容,其 content 的类型应为 Content

When declaring Message, if its type is content, its content's type should be Content.

let message = Message(
    type: .content,
    content: Content( ... )
}

类型请求时,其内容的类型应为 Request

let message = Message(
    type: .request,
    content: Request( ... )
}

然后,如何设置 content 属性的类型?

Then, How should I set content property's type?

我试图像这样使它成为 String

I tried to make it as String like this way :

struct Message: Codable{
    var type: MessageType
    var content: String
}

struct Content: Codable{
    var jsonString: String{
        return String(data: try! JSONEncoder().encode(self), encoding: .utf8)
    }
}

let foo = Message(
    var type: .content,
    var content: Content ( ... ).jsonString
)

,我可以使用它,但是我知道要在Android等不同平台上使用它,所以我想获得一种更智能的方式来处理它。

and I could use it, But I'm aware of using it in different platforms like Android, So I want to get more smart way to deal with this.

推荐答案

使用如下通用名称:

struct Message<T:Codable>: Codable{
    var type: MessageType
    var content: T
}

这篇关于创建具有通用类型的可编码结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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