使用Decodable在Realm中保存对象数组 [英] Saving array of objects in Realm with Decodable

查看:192
本文介绍了使用Decodable在Realm中保存对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个符合Decodable协议(从API提取数据)的类,我想将其保存在Realm数据库中。当我的属性之一是数组(列表)时,会发生问题。它说由于List< Item>不能自动合成Decodable。不符合Decodable
绕过此问题的最佳方法是什么?领域仅支持基本类型的数组。

I've got a class which conforms to Decodable protocol (fetching data from API) and I would like to save it in the Realm database. Problem occurs when one of my properties is array (List). It says Cannot automatically synthesize Decodable because List<Item> does not conform to Decodable What is the best way to bypass this problem? Realm only supports arrays of primitive types.

这是我的课程:

class PartValue: Object, Decodable {
    @objc dynamic var idetifier: Int = 0
    let items = List<Item>()
}


推荐答案

使用在Swift 4.1中实现的期待已久的条件一致性,只需声明列出以符合可解码,以防其元素符合可分解的

Using the long awaited conditional conformances implemented in Swift 4.1, you can simply declare List to conform to Decodable in case its Element conforms to Decodable.

extension List: Decodable where List.Element: Decodable {
    public convenience init(from decoder: Decoder) throws {
        self.init()
        var container = try decoder.unkeyedContainer()
        let array = try container.decode(Array<Element>.self)
        self.append(objectsIn: array)
    }
}

要针对您的特定情况进行这项工作,您需要确保 I tem 也符合 Decodable

To make this work for your specific case, you need to make sure that Item also conforms to Decodable.

如果您还需要可编码一致性,只需扩展 List 来支持它。

If you also need Encodable conformance, simply extend List to support that as well.

extension List: Encodable where List.Element: Encodable {
    public func encode(to encoder: Encoder) throws {
        var container = encoder.unkeyedContainer()
        try container.encode(contentsOf: Array(self))
    }
}

这篇关于使用Decodable在Realm中保存对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆