情境 (Scenario)
I know this is not everyday scenario that we face but there can be many situation where you may have implement this kind of behavior instead of duplicating same contextual models with weird names and have redundant code. Example
我知道这不是我们每天都会遇到的情况,但是在许多情况下,您可能已经实现了这种行为,而不是使用怪异的名称复制相同的上下文模型并使用了多余的代码。 例
An App accessing user data from two different sources with different JSON object even though the user is same in those different sources. Example: A super app providing services from different services provided user is having account on those services
一个App从具有不同JSON对象的两个不同来源访问用户数据,即使这些不同来源中的用户相同。 示例 :提供来自不同服务的服务的超级应用程序(如果用户拥有这些服务)
In scenario like this you will be working with different API endpoint of these services and parse the JSON.
在这种情况下,您将使用这些服务的不同API终结点并解析JSON。
So the question is how will achieve this with Decodable?
那么问题是如何用Decodable实现呢?
让我们开始解码 (Let’s Start Decoding)
In the below example gist, I have added two scenarios of user JSON we will receive in our app from different scenarios. Now what we did is
在下面的示例要点中,我添加了两种用户JSON场景,我们将从不同的场景中接收到我们的应用程序。 现在我们要做的是
We created a user object which implements
Decodable
with keys we need to parse in it.我们创建了一个用户对象,该对象使用需要解析的键来实现
Decodable
。We created two different
CodingKeys
for our case as we are expecting two different sources, In this caseServiceOneCodingKeys
andServiceTwoCodingKeys
which handle the user object for this two different services.我们为我们的案例创建了两个不同的
CodingKeys
,因为我们期望有两个不同的来源,在这种情况下,ServiceOneCodingKeys
和ServiceTwoCodingKeys
可以处理这两个不同服务的用户对象。Now comes the Important part where we implement custom
init(from decoder: Decoder)
, In this we implement custom strategy to decode our user object with two different JSON, The implementation is straight forward as you can see we first decode it first with ServiceOne container and verify any variable in this caseuserId
and if we found itnil
we move towards to second container.现在是重要部分,我们在其中实现了自定义
init(from decoder: Decoder)
,在此我们实现了自定义策略,以使用两个不同的JSON解码用户对象,实现非常简单,因为您可以看到我们首先使用ServiceOne容器对其进行了解码并验证在这种情况下,任何变量userId
,如果我们发现它nil
我们朝着第二容器移动。Lastly if none of container works we send
fatalError
in this case, We can also send crash report to verify the unknown issues.最后,如果在这种情况下没有容器可以正常工作,我们将发送
fatalError
,我们也可以发送崩溃报告以验证未知问题。
感谢您的阅读 (Thank you for reading)
I hope this article helps you, You can copy the gist in Xcode playground and have a hands on with your custom scenarios.
希望本文对您有所帮助,您可以在Xcode操场上复制要点,并尝试使用自定义方案。