【发布时间】:2022-01-16 17:22:54
【问题描述】:
我有以下 Codable 协议,其中包含一个我想从可编码协议中排除的变量。
问题是我无法在我自己的协议中使用为此创建的 CodingKeys 枚举:Type 'CodingKeys' cannot be nested in protocol 'Animal'。
protocol Animal: Codable {
var name: String { get set }
var color: String { get }
var selfiePicture: Selfie { get }
// Not possible
enum CodingKeys: String, CodingKey {
case name
case color
}
}
我该如何解决这个问题?
编辑更多代码和更具体的例子
Animal 被多个结构使用(不能是类):
struct Frog: Animal {
var name: String
var color: String
// extra variables on top of Animal's ones
var isPoisonous: Bool
var selfiePicture = [...]
}
它也被用作另一个顶级编码对象上的变量数组:
final class Farm: Codable {
var address: String
// more variables
var animals: [Animal]
enum CodingKeys: String, CodingKey {
case address
case animals
}
convenience init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
address = try values.decode(String.self, forKey: .address)
animals = try values.decode([Animal].self, forKey: .animals) // ERROR --> Protocol 'Animal' as a type cannot conform to 'Decodable'
}
}
【问题讨论】:
-
在这里查看协议中的嵌套类型:stackoverflow.com/questions/31845066/…
-
如果您使用
class并手动实现Codable,则可以共享密钥。那么任何其他共享的类都可以使用键继承class -
@Iorem 我不能,因为
MyProtocol被结构而不是类使用。 -
为了更精确,我编辑了我的问题。
-
您不需要协议,使用
struct Animal并添加一个属性type,它可以是您所有类型动物的枚举
标签: swift enums protocols codable