- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
以下代码无法编译:
enum Occupation: String {
case designer = "Designer"
case engineer = "Engineer"
}
public struct SteveJobs: Codable {
let name: String
let occupation: Occupation
}
另一方面,它应该编译,因为 Occupation
表示为 String
,它是 Codable
。
为什么我不能在 Codable
结构中使用带有原始值的 enum
?
特别是为什么自动一致性在这种情况下不起作用。
最佳答案
自动 Codable
合成是“选择加入”的,即您必须声明明确的一致性:
enum Occupation: String, Codable { // <--- HERE
case designer = "Designer"
case engineer = "Engineer"
}
public struct SteveJobs: Codable {
let name: String
let occupation: Occupation
}
参见 SE-0166 Swift Archival & Serialization
By adopting these protocols, user types opt in to this system.
自动Hashable
和Equatable
合成也是如此,比较 Requesting synthesis is opt-in在 SE-0185 中,其中列出了一些原因:
The syntax for opting in is natural; there is no clear analogue in Swift today for having a type opt out of a feature.
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.
关于ios - 具有原始值的枚举,可编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50724245/
我是一名优秀的程序员,十分优秀!