我有一个协议,名为Codable并且一个类,也名为Codable :
public protocol SourceListItem: AnyObject, Codable
{
var name: String { get set }
var children: [SourceListItem] { get set }
}
final public class SourceListHeader: Codable
{
var name: String = "Give me a name!"
var children: [SourceListItem] = [SourceListItem]()
}
然而,编译器给了我两个错误:
Type 'SourceListHeader' does not conform to protocol 'Decodable'
Type 'SourceListHeader' does not conform to protocol 'Codable'
为什么会这样呢?我无法解决这个错误,而且我已经尝试了很多不同的方法...
问题似乎来自于协议,因为如果我去掉它,一切都正常。就好像编译器不能理解该协议仅适用于Codable类。
class SourceListHeader<Item: SourceListItem>:Codable
和使用var children: [Item] = [Item]()
以及声明class SourceListHeader:Codable
和使用var children: [SourceListItem] = [SourceListItem]()
有什么区别?对我来说,看起来<Item: SourceListItem>
只是告诉编译器Item符合SourceListItem
的要求...这与var children: [SourceListItem]
相同。 - AdelineItem
是符合Codable
协议的具体类型,而SourceListItem
是继承自Codable
协议的协议。然而,协议本身不符合自己,因此需要使用泛型。 - Dávid Pásztor