【问题标题】:How do I make an enum codable? [duplicate]如何使枚举可编码? [复制]
【发布时间】:2020-07-12 09:27:11
【问题描述】:

我在struct 中有一个嵌套的enum,我想符合Codable。如何使枚举 codable 并因此使 struct 可编码?

这是我所拥有的一个例子:

struct Person: Codable {
  var firstName: String
  var lastName: String 
  var favoriteColor: Color

  enum Color {
    case blue, red, green, yellow, pink, purple
  }
}

然后,我得到两个错误:

类型“Person”不符合协议“Decodable”

类型“Person”不符合协议“Encodable”

我该如何解决这个问题?

编辑

我也尝试过让 Color 符合 Codable。 Xcode 添加了这些协议存根:

init(from decoder: Decoder) throws {
  <#code#>
}
func encode(to encoder: Encoder) throws {
  <#code#>
}

我会用这个做什么?

【问题讨论】:

  • 您是否尝试将Codable 添加到Color
  • 你的意思是让 Color 符合 Codable 协议吗?
  • 我该怎么做?
  • enum Color: String, Codable (或您想使用的任何原始值)。如果您不想使用可编码的原始值,则必须自己实现解码/编码。

标签: ios swift xcode enums encode


【解决方案1】:
struct Person: Codable {
     var firstName: String
     var lastName: String
     var favoriteColor: Color
}

enum Color: String, Codable {
   case blue, red, green, yellow, pink, purple
}

【讨论】:

  • 这对我的 Color 枚举有什么作用?这会以任何方式修改它吗?
  • 它声明Color枚举值是一个String
  • 请注意:枚举不需要在结构声明中声明。
  • @nighttalker 你是绝对正确的,谢谢你提到它。我编辑了我的答案。
  • 请注意,在结构中定义它也没有错。真的取决于上下文。如果这个枚举是特定于 Person 的,那么它也可能是嵌套的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多