具有原始值的枚举,可编码

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

为什么我不能在 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.

自动HashableEquatable合成也是如此, 比较 SE-0185 中的 Requesting synthesis is opt-in,其中 列出了一些原因:

  • 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.