Enum with Raw value, Codable

回眸只為那壹抹淺笑 提交于 2019-12-20 03:52:30

问题


The following code doesn't compile:

enum Occupation: String {
  case designer = "Designer"
  case engineer = "Engineer"
}

public struct SteveJobs: Codable {
  let name: String
  let occupation: Occupation
}

On the other hand, it should compile since the Occupation is represented as a String which is Codable.

Why can't I use enum with raw value in Codable structs?

In particular, why automatic conformance isn't working in such a case.


回答1:


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
}

See SE-0166 Swift Archival & Serialization

By adopting these protocols, user types opt in to this system.

The same is true for automatic Hashable and Equatable synthesis, compare Requesting synthesis is opt-in in SE-0185, where some reasons are listed:

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



来源:https://stackoverflow.com/questions/50724245/enum-with-raw-value-codable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!