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
}

另一方面,它应该编译,因为职业表示为String,它是可编码

为什么我不能在 Codable 结构中使用带有原始值的 enum

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

error

最佳答案

自动可编码合成是“选择加入”,即您必须声明 明确的一致性:

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/55269075/

相关文章:

ios - UIImagePickerController,我可以使用它来拍照并将它们保存到我的应用程序中的路径中,而不必将它们保存在照片应用程序中吗?

ios - 使用 swift 从 Game Center 检索用户最高分

ios - touchesMoved 在 iPhone 6s 及以后的设备上被调用

ios - Swift-Access UILabels 在 UITableView 的动态单元格中

iOS 自定义快捷键输入/输出值

ios - Swift 4 - 通过 UIActivityViewController 共享位置

ios - Swift iOS - 如何将 NSTextAttachment 内容模式设置为 Aspect Fit?

Java 枚举初始化最佳实践

ruby - 在 ruby​​ 中,你将相关符号(如 java 中的枚举)放在哪里?

C++ 使用 int 从列表中设置枚举