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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…