具有原始值的枚举,可编码 [英] Enum with Raw value, Codable
问题描述
以下代码无法编译:
enum Occupation: String {
case designer = "Designer"
case engineer = "Engineer"
}
public struct SteveJobs: Codable {
let name: String
let occupation: Occupation
}
另一方面,自 Occupation 表示为
String
,它是 Codable
。
On the other hand, it should compile since the Occupation
is represented as a String
which is Codable
.
为什么我不能使用枚举
在 Codable
结构中使用原始值?
Why can't I use enum
with raw value in Codable
structs?
尤其是为什么自动一致性在这种情况下不起作用。
推荐答案
自动 Codable
合成是选择加入,即您必须明确声明
符合性:
Automatic Codable
synthesis is "opt-in," i.e. you have to declare the
conformance explicitly:
enum Occupation: String, Codable { // <--- HERE
case designer = "Designer"
case engineer = "Engineer"
}
public struct SteveJobs: Codable {
let name: String
let occupation: Occupation
}
通过采用这些协议,用户类型可以选择加入该系统。
By adopting these protocols, user types opt in to this system.
对于自动 Hashable
和 Equatable
自动合成也是如此,
比较在SE-0185中选择了请求合成,其中列出了
的某些原因:
The same is true for automatic Hashable
and Equatable
synthesis,
compare Requesting synthesis is opt-in in SE-0185, where
some reasons are listed:
选择加入的语法很自然;如今
Swift中没有明确的类似物,因为它选择了退出某项功能。
The syntax for opting in is natural; there is no clear analogue in Swift today for having a type opt out of a feature.
这需要用户有意识地决定公共API
的类型会浮出水面。类型不能意外地落入用户不希望的
一致性;可以在以后更改最初不支持
的类型,但
的反向更改是一项重大更改。
It requires users to make a conscious decision about the public API surfaced by their types. Types cannot accidentally "fall into" conformances that the user does not wish them to; a type that does not initially support Equatable can be made to at a later date, but the reverse is a breaking change.
通过检查
的源代码,可以清楚地看到类型支持的一致性;
The conformances supported by a type can be clearly seen by examining its source code; nothing is hidden from the user.
我们减少了编译器的工作量,并减少了由于不合成非一致性而产生的代码
的数量。
We reduce the work done by the compiler and the amount of code generated by not synthesizing conformances that are not desired and not used.
这篇关于具有原始值的枚举,可编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!