本文介绍了如何使枚举可编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 struct
中嵌套了一个 enum
,我希望它符合 Codable
.如何使枚举 codable
从而使 struct
可编码?
I have a nested an enum
inside a struct
that I want to conform to Codable
. How do I make the enum codable
and therefore make the struct
codable?
这是我所拥有的示例:
struct Person: Codable {
var firstName: String
var lastName: String
var favoriteColor: Color
enum Color {
case blue, red, green, yellow, pink, purple
}
}
然后,我得到两个错误:
Then, I get two errors :
类型人"不符合协议可解码"
类型人"不符合协议可编码"
Type 'Person' does not conform to protocol 'Encodable'
我该如何解决这个问题?
How can I fix this problem?
编辑
我也尝试过使 Color 符合 Codable.Xcode 添加了这些协议存根:
I have also tried conforming Color to Codable. Xcode adds these protocol stubs:
init(from decoder: Decoder) throws {
<#code#>
}
func encode(to encoder: Encoder) throws {
<#code#>
}
我该怎么办?
推荐答案
struct Person: Codable {
var firstName: String
var lastName: String
var favoriteColor: Color
}
enum Color: String, Codable {
case blue, red, green, yellow, pink, purple
}
这篇关于如何使枚举可编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!