Create codable struct with generic type

本小妞迷上赌 提交于 2019-12-03 17:54:07

问题


First of all, Sorry for unclear title of question

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

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

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

When type is request, its content's type should be Request.

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

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

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
)

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.


回答1:


Use generic like below:

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



回答2:


Try this, in Message Struct

var content: [String: Any]


来源:https://stackoverflow.com/questions/50674721/create-codable-struct-with-generic-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!