本文介绍了具有原始值的枚举,可编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码无法编译:

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 theconformance explicitly:

enum Occupation: String, Codable { // <--- HERE
    case designer = "Designer"
    case engineer = "Engineer"
}

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

请参见

对于自动 Hashable 和 Equatable 自动合成也是如此,
比较,其中列出了
的某些原因:

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

这需要用户有意识地决定公共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.

这篇关于具有原始值的枚举,可编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:07