【发布时间】:2020-05-07 17:43:07
【问题描述】:
我有带有 2 个变量的 Application 协议。我有component 结构,它有一个变量,它确认Application 协议。我需要将此struct 保存在磁盘中。所以我将其确认为Codable 协议。这样做时,我遇到了这样的错误,
“协议类型'Application'不能符合'Decodable',因为只有具体类型才能符合协议”
这是我的代码,
public protocol Application {
var name : String {get}
var ownerName : String {get}
}
public struct component : Codable {
let application : Application
private enum CodingKeys: String, CodingKey {
case application
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
application = try values.decode(Application.self, forKey: .application)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(application, forKey: .application)
}
}
我是 swift 新手,如果我遗漏了一些非常明显的东西,我很抱歉。我无法解决这个问题,我需要一些正确方向的帮助。先感谢您。
【问题讨论】:
-
你也可以粘贴你的json吗?
-
"只有具体类型才能符合协议" - 所以在这里使用具体类型。
-
Application不是Codable所以component不可能。 -
为什么要使用协议?而不是结构?
-
应用程序需要是一个符合 codable 的结构,或者将其更改为符合要求的结构。
标签: ios swift codable decodable encodable