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

标签 ios swift enums swift-protocols 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

特别是为什么自动一致性在这种情况下不起作用。

error

最佳答案

自动 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合成也是如此, 比较 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/

相关文章:

Ios - 对 nib 文件中按钮的操作

ios - Xcode 11 - 实例方法...与另一个类别的相同方法冲突

ios - 如何调整 JSQ Messages CollectionViewCell 的气泡边距

ios - 实现 SlideView 动画 SlideFromTop 和 SlideFromBottom

arrays - 我如何使 Firebase 中的 .observe 在调用重新加载 Collection View 之前检索其所有数据

c# - 使用 MVC 根据枚举值定义 HTML 元素颜色

ios - Pan Segue 调用 viewDidLoad 循环

ios - 在具有 Storyboard segue 的 collectionviewcell super View 上带有推送 Segue 的按钮会引发错误

java - 枚举类型设置为 int 数组

swift - 端点构建器 Swift