Cyan Lee
Cyan Lee

Reputation: 341

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.

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.

Upvotes: 1

Views: 2263

Answers (2)

Muhammad Shauket
Muhammad Shauket

Reputation: 2778

Try this, in Message Struct

var content: [String: Any]

Upvotes: 0

SPatel
SPatel

Reputation: 4956

Use generic like below:

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

Upvotes: 9

Related Questions