所以我有一个大致结构的协议:
protocol Content: Codable {
var type: ContentType { get }
associatedtype ContentData: Codable
var data: ContentData { get set }
var id: UUID { get }
...
}我有一个像这样的枚举:
enum ContentType: String, Equatable, CaseIterable, Codable, RawRespresentable {
case type1 = "Type 1"
case type2 = "Type 2"
}然后,我有一个使用Swift新的5.7语法的对象,它保存了Content的混合类型,如下所示:
class ContentCollection: Codable {
var contents: [any Content]
...
}因此,我能够从任何any Content的类型属性中破译出它是哪种类型的内容,并按如下方式正确地进行类型转换:
for content in contents {
switch content.type {
case .type1:
let typedContent = content as! Type1
try container.encode(typedContent, forKey: .contents)
case .type2:
let typedContent = content as! Type2
try container.encode(typedContent, forKey: .contents)
...
}
}但这只是在整个数组上编写单个内容。如何一次编码单个片段并将其添加到JSON数组中?我是个新手,所以如果我错过了一些显而易见的东西,请原谅。
同样的,你会怎么把它解码回来?
谢谢!
发布于 2022-09-14 01:57:08
@清道夫回答了这个问题。
为了解码我做了这样的事:
var contentsContainer = try container.nestedUnkeyedContainer(forKey: .contents)
var contents: [any Content] = []
while !contentsContainer.isAtEnd {
// try to decode as every type of Content
contents.append(try contentsContainer.decode(ContentType1.self))
contents.append(try contentsContainer.decode(ContentType2.self))
contents.append(try contentsContainer.decode(ContentType3.self))
}
self.contents = contents我做了这样的编码:
var contentsContainer = container.nestedUnkeyedContainer(forKey: .contents)
for content in contents {
switch content.type {
case .contentType1:
try contentsContainer.encode(content as! ContentType1)
case .contentType2:
try contentsContainer.encode(content as! ContentType2)
case .contentType3:
try contentsContainer.encode(content as! ContentType3)
}
}https://stackoverflow.com/questions/73710307
复制相似问题