gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:13:14 25 4
gpt4 key购买 nike

以下代码无法编译:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com