swift - 使类可编码

标签 swift codable decodable

我有一个协议(protocol),即 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'

这是为什么呢?我无法修复错误,并且我尝试了很多变体...

问题似乎出在协议(protocol)上,因为如果我删除它,一切正常。这就像编译器没有看到该协议(protocol)仅适用于 Codable 类。

最佳答案

你需要一个符合Codable的具体类型,你不能使用一个符合Codable的协议(protocol)。

final public class SourceListHeader<Item: Codable>: Codable {
    var name: String = "Give me a name!"
    var children = [Item]()
}

关于swift - 使类可编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56758507/

相关文章:

ios - 保存结构的最快方法 iOS/Swift

swift - 无法使用 Swift Codable 解析响应

ios - 作为类型扩展的 Swift 2.0 协议(protocol)

ios - 无法通过对象链接查询 NSData 属性

swift - NSCoding 和 Codable 可以共存吗?

ios - 将结构体设置为可编码/可解码而不只是可编码是否有任何性能优势?

json - Swift 解码具有混合类型和可能的子结构的 JSON

swift - iOS Swift 获取惰性 map 集合值

python - 如何在 swift 应用程序中运行 python 脚本?

swift - 如何使 RealmSwift RealmOptional 与 Swift Codable 兼容?