可编码类不符合协议可解码 [英] Codable class does not conform to protocol Decodable
问题描述
为什么我收到类型'书签'不符合协议'可解码'错误消息?
Why am I getting a "Type 'Bookmark' does not conform to protocol 'Decodable'" error message?
class Bookmark: Codable {
weak var publication: Publication?
var indexPath: [Int]
var locationInText = 0
enum CodingKeys: String, CodingKey {
case indexPath
case locationInText
}
init(publication: Publication?, indexPath: [Int]) {
self.publication = publication
self.indexPath = indexPath
}
}
我不希望保存出版物var,因为出版物拥有书签,但是书签需要知道它属于哪个出版物。
I do not wish to save the publication var since the Publication owns the Bookmark but the bookmark needs to know which Publication it belongs to. The decode init of Publication will set the bookmark reference to itself.
推荐答案
为什么我得到一个错误消息类型'书签'不符合协议'可解码的'
Why am I getting a "Type 'Bookmark' does not conform to protocol 'Decodable'" error message
这是因为出版物不可解码(您有没有显示它是什么,所以很难说)或由于出版物
上的弱
名称。
It's either because Publication isn't Decodable (you have not shown what it is, so it's hard to tell) or because of the weak
designation on publication
.
无论哪种方式,都很容易修复:您只需要实现 init(from:)
即可完成Decodable的实现;编译器只是告诉您该实现无法综合。
Either way, it's easy to fix: you just need to implement init(from:)
to complete the implementation of Decodable; the compiler is simply telling you that this implementation cannot be synthesized.
这篇关于可编码类不符合协议可解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!