Enum with Raw value, Codable

前端 未结 1 1227
深忆病人
深忆病人 2021-01-23 20:59

The following code doesn\'t compile:

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

public struct SteveJobs: Codable          


        
相关标签:
1条回答
  • 2021-01-23 21:24

    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.

    0 讨论(0)
提交回复
热议问题