如果我想从 Codable 中排除一些属性,为什么这些属性必须是可选的?
If I want to exclude some properties from Codable, why those properties must be Optional?
我有以下struct
struct Checklist : Codable {
let id: Int64
var text: String?
var checked: Bool
var visible: Bool
var version: Int64
private enum CodingKeys: String, CodingKey {
case id
case text
case checked
}
}
但是,我遇到了编译器错误
Type 'Checklist' does not conform to protocol 'Decodable'
我能解决的唯一方法是将排除的属性更改为可选。
struct Checklist : Codable {
let id: Int64
var text: String?
var checked: Bool
var visible: Bool?
var version: Int64?
private enum CodingKeys: String, CodingKey {
case id
case text
case checked
}
}
请问这是为什么?这是解决此类编译器错误的唯一正确方法吗?
它们不需要是可选项,但它们必须有一些初始值,例如
struct Checklist : Codable {
let id: Int64
var text: String?
var checked: Bool
var visible: Bool = false
var version: Int64 = 0
private enum CodingKeys: String, CodingKey {
case id
case text
case checked
}
}
否则,当通过合成
从外部表示创建实例时,这些属性将是未定义的
init(from decoder: Decoder)
方法。或者,您可以自己实现该方法,确保所有属性都已初始化。
Optionals 有一个隐含的初始值 nil
,这就是为什么你的解决方案也有效。
我有以下struct
struct Checklist : Codable {
let id: Int64
var text: String?
var checked: Bool
var visible: Bool
var version: Int64
private enum CodingKeys: String, CodingKey {
case id
case text
case checked
}
}
但是,我遇到了编译器错误
Type 'Checklist' does not conform to protocol 'Decodable'
我能解决的唯一方法是将排除的属性更改为可选。
struct Checklist : Codable {
let id: Int64
var text: String?
var checked: Bool
var visible: Bool?
var version: Int64?
private enum CodingKeys: String, CodingKey {
case id
case text
case checked
}
}
请问这是为什么?这是解决此类编译器错误的唯一正确方法吗?
它们不需要是可选项,但它们必须有一些初始值,例如
struct Checklist : Codable {
let id: Int64
var text: String?
var checked: Bool
var visible: Bool = false
var version: Int64 = 0
private enum CodingKeys: String, CodingKey {
case id
case text
case checked
}
}
否则,当通过合成
从外部表示创建实例时,这些属性将是未定义的init(from decoder: Decoder)
方法。或者,您可以自己实现该方法,确保所有属性都已初始化。
Optionals 有一个隐含的初始值 nil
,这就是为什么你的解决方案也有效。