给出一个结构,该结构具有共享名称的static和instance属性:
struct MyStruct {
// The version on the type
static let version = 1
// The version on the instance based on the static version
var version: Int = MyStruct.version
}
如果我添加自定义Codable
一致性,则容器将比实例var更喜欢静态。例如:
extension MyStruct: Codable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(version, forKey: .version)
}
enum CodingKeys: String, CodingKey {
case version
}
}
然后去编码一个实例:
let myStruct = MyStruct(version: 2)
let encoded = try! JSONEncoder().encode(myStruct)
try! JSONDecoder().decode(MyStruct.self, from: encoded) // MyStruct version 1
我可以通过自我container.encode(self.version, forKey: .version)
进行排位赛来解决此问题。但这不是重点。
这很奇怪。为什么会这样呢?