首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在SWIFT5.7中编码/解码类型为[任意TypeName]的异构数组的最佳方法是什么?

在SWIFT5.7中编码/解码类型为[任意TypeName]的异构数组的最佳方法是什么?
EN

Stack Overflow用户
提问于 2022-09-14 00:31:15
回答 1查看 73关注 0票数 0

所以我有一个大致结构的协议:

代码语言:javascript
复制
protocol Content: Codable {

    var type: ContentType { get }    
    associatedtype ContentData: Codable
    var data: ContentData { get set }
    var id: UUID { get }

    ...
}

我有一个像这样的枚举:

代码语言:javascript
复制
enum ContentType: String, Equatable, CaseIterable, Codable, RawRespresentable {
    case type1 = "Type 1"
    case type2 = "Type 2"
}

然后,我有一个使用Swift新的5.7语法的对象,它保存了Content的混合类型,如下所示:

代码语言:javascript
复制
class ContentCollection: Codable {
    var contents: [any Content]
    ...
}

因此,我能够从任何any Content的类型属性中破译出它是哪种类型的内容,并按如下方式正确地进行类型转换:

代码语言:javascript
复制
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数组中?我是个新手,所以如果我错过了一些显而易见的东西,请原谅。

同样的,你会怎么把它解码回来?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-14 01:57:08

@清道夫回答了这个问题。

为了解码我做了这样的事:

代码语言:javascript
复制
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

我做了这样的编码:

代码语言:javascript
复制
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)
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73710307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档