我一直Codable
很高兴在我当前的项目中使用 s - 一切都很好,我开箱即用的大部分东西都是内置的 - 完美!不过,最近我偶然发现了第一个真正的问题,无法按照我想要的方式自动解决。
问题描述
我有一个来自后端的 JSON,它是一个嵌套的东西。看起来像这样
{
"id": "fef08c8d-0b16-11e8-9e00-069b808d0ecc",
"title": "Challenge_Chapter",
"topics": [
{
"id": "5145ea2c-0b17-11e8-9e00-069b808d0ecc",
"title": "Automation_Topic",
"elements": [
{
"id": "518dfb8c-0b18-11e8-9e00-069b808d0ecc",
"title": "Automated Line examle",
"type": "text_image",
"video": null,
"challenge": null,
"text_image": {
"background_url": "",
"element_render": ""
}
},
{
"id": "002a1776-0b18-11e8-9e00-069b808d0ecc",
"title": "Industry 3.0 vs. 4.0: A vision of the new manufacturing world",
"type": "video",
"video": {
"url": "https://www.youtube.com/watch?v=xxx",
"provider": "youtube"
},
"challenge": null,
"text_image": null
},
{
"id": "272fc2b4-0b18-11e8-9e00-069b808d0ecc",
"title": "Classmarker_element",
"type": "challenge",
"video": null,
"challenge": {
"url": "https://www.classmarker.com/online-test/start/",
"description": null,
"provider": "class_marker"
},
"text_image": null
}
]
}
]
}
Chapter是根对象,它包含一个Topics列表,每个主题都包含一个Elements列表。非常简单,但我被最低级别的Elements卡住了。每个Element都有一个来自后端的枚举,如下所示:
[ video, challenge, text_image ]
,但 iOS 应用程序不支持挑战,因此我在 Swift 中的ElementType枚举如下所示:
public enum ElementType: String, Codable {
case textImage = "text_image"
case video = "video"
}
当然,它throws
,因为发生的第一件事是它试图解码challenge
这个枚举的值并且它不存在,所以我的整个解码失败了。
我想要
的
只是希望解码过程忽略 Element
无法解码的 s 。我不需要任何Optional
s。我只是希望它们不会出现在 Topic 的元素数组中。
我的推理和它的缺点
当然,我已经做了几次尝试来解决这个问题。第一个,最简单的只是标记ElementType
为Optional
,但是稍后使用这种方法我将不得不打开所有内容并处理它 - 这是一项相当乏味的任务。我的第二个想法是.unsupported
在我的枚举中有类似 case 的东西,但是稍后我想用它来生成单元格,我将不得不throw
或返回Optional
- 基本上,与以前的想法相同的问题。我的最后一个想法,但我还没有测试过,是编写一个init()
可解码的自定义并以某种方式在那里处理它,但我不确定它是否Element
应该Topic
对此负责?如果我把它写进去Element
,我不能返回任何东西,我将不得不throw
,但如果我把它放进去,Topic
我必须append
成功地将元素解码为数组。问题是,如果在某个时候我将直接获取,将会发生什么- 再次,如果没有ing Elements
,我将无法做到这一点。throw
TL;DR
我不想init(from decoder: Decoder) throws
,throw
但要返回Optional
。