【发布时间】: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