简体   繁体   English

创建具有通用类型的可编码结构

[英]Create codable struct with generic type

First of all, Sorry for unclear title of question 首先,很抱歉问题标题不清楚

I'm making a codable struct which will be used as json message. 我正在制作一个可编码的结构,它将用作json消息。

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 {...}

When declaring Message , if its type is content , its content 's type should be Content . 声明Message ,如果其typecontent ,则其content类型应为Content

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

When type is request , its content 's type should be Request . typerequest ,其content的类型应为Request

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

Then, How should I set content property's type? 然后,如何设置content属性的类型?

I tried to make it as String like this way : 我试图这样使它成为String

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
)

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. 我可以使用它,但是我知道要在Android等不同平台上使用它,所以我想找到一种更智能的方式来处理它。

Use generic like below: 使用如下通用名称:

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

消息结构中尝试一下

var content: [String: Any]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM