【问题标题】:Create codable struct with generic type创建具有泛型类型的可编码结构
【发布时间】:2018-11-13 10:38:05
【问题描述】:

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

我正在制作一个可编码的结构,它将用作 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 {...}

在声明Message时,如果其type为content,则其content的类型应为Content。

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

当type 为request 时,其content 的类型应为Request。

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

那么,我应该如何设置content属性的类型呢?

我试着像这样把它变成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
)

我可以使用它,但我知道在 Android 等不同平台上使用它,所以我想用更聪明的方式来处理这个问题。

【问题讨论】:

  • 内容和请求是字典?
  • 不,Content 和 Request 也是可编码结构。
  • 顺便说一下可编码结构总是字典
  • 将其用作动态尝试此 [string: Any] ,然后映射您的对象
  • 哎呀,我试试看。

标签: swift codable


【解决方案1】:

像下面这样使用泛型:

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

【讨论】:

  • 非常感谢,我不知道泛型!
【解决方案2】:

试试这个,在 Message 结构中

var content: [String: Any]

【讨论】:

  • 感谢您的帮助,但它给了我Type 'Message' does not conform to protocol 'Decodable' 错误;(
  • 因为没有在消息结构中定义键
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多