可解码 - 继承阻止解码器初始化合成
Decodable - inheritance prevents decoder init from synthesizing
我有以下 Swift 4 Codable
class,它继承自 Realm 的对象类型:
final class SearchResult: RealmSwift.Object, Codable {
@objc dynamic var name: String = ""
@objc dynamic var region: String = ""
enum CodingKeys: String, CodingKey {
case name = "name"
case region = "region"
}
}
这里的期望是 init(from decoder: Decoder)
方法被合成,这样我就不必自己实现它,这是一个巨大的便利。但是,不实现它会产生以下编译器错误:
super.init isn't called on all paths before returning from initializer
有三种方法可以 git 消除编译器错误,但是 none 其中的方法是好的:
实现一个空的 init(from decoder: Decoder)
方法,它只调用 super.init()
。这似乎阻止了合成,这意味着实际上没有任何内容被解码,因为它只是一个空方法。
手动实现整个init(from decoder: Decoder)
方法。这行得通,但现在使用 Codable
的乐趣几乎消失了。
删除所有与 Realm 相关的代码。现在 Codable 可以按预期工作,但是,现在我不能再使用 Realm 了。
这对我来说似乎是一个 Swift 错误,因为它应该检测到 init(from decoder: Decoder)
实际上正在实施,而不是手动实施。
有什么我不知道的建议或解决方法吗?
这似乎已在 Xcode 9 GM 中解决,它现在允许在使用 required init()
方法从 类 继承时由 Codable 合成初始化器。
我有以下 Swift 4 Codable
class,它继承自 Realm 的对象类型:
final class SearchResult: RealmSwift.Object, Codable {
@objc dynamic var name: String = ""
@objc dynamic var region: String = ""
enum CodingKeys: String, CodingKey {
case name = "name"
case region = "region"
}
}
这里的期望是 init(from decoder: Decoder)
方法被合成,这样我就不必自己实现它,这是一个巨大的便利。但是,不实现它会产生以下编译器错误:
super.init isn't called on all paths before returning from initializer
有三种方法可以 git 消除编译器错误,但是 none 其中的方法是好的:
实现一个空的
init(from decoder: Decoder)
方法,它只调用super.init()
。这似乎阻止了合成,这意味着实际上没有任何内容被解码,因为它只是一个空方法。手动实现整个
init(from decoder: Decoder)
方法。这行得通,但现在使用Codable
的乐趣几乎消失了。删除所有与 Realm 相关的代码。现在 Codable 可以按预期工作,但是,现在我不能再使用 Realm 了。
这对我来说似乎是一个 Swift 错误,因为它应该检测到 init(from decoder: Decoder)
实际上正在实施,而不是手动实施。
有什么我不知道的建议或解决方法吗?
这似乎已在 Xcode 9 GM 中解决,它现在允许在使用 required init()
方法从 类 继承时由 Codable 合成初始化器。