如何将列表类型与Codable结合使用? (RealmSwift) [英] How to use List type with Codable? (RealmSwift)

查看:133
本文介绍了如何将列表类型与Codable结合使用? (RealmSwift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是列表类型不符合Codable,下面的类不能插入到Realm中.

Problem is List type does not conform to Codable, the below class cannot be insert to Realm.

例如,

class Book: Codable {
    var name: String = ""
    var author: String = ""
    var tags = [String]()
}

考虑上述类符合Codable,如果将该类存储到Realm,则需要使用List<Object>类型而不是[String]

Consider the above class conforms to Codable, if store this class to Realm, it needs to use List<Object> type instead of [String]

class Book: Object, Codable {
    @objc dynamic var name: String = ""
    @objc dynamic var author: String = ""
    var tags = List<Tag>()

    required convenience init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        author = try container.decode(String.self, forKey: .author)
        tags = try container.decode(List<Tag>.self, forKey: .tags)   // this is problem.
    }
}

class Tag: Object, Codable {
    @objc dynamic var string: String = ""

    required convenience init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        string = try container.decode(String.self, forKey: .string)
    }
}

要符合Codable,应实现Decodable协议. (required convenience init(from decoder: Decoder) throws)

To conform to Codable, it should be implement Decodable protocol. (required convenience init(from decoder: Decoder) throws)

但是,List类型不符合Codable(Decodable),如果类具有List类型,则无法使用Codable.

But, List type does not conform to Codable(Decodable), it is impossible to use Codable if the class has List type.

如何解决此问题?

谢谢

推荐答案

您快到了.在初始化程序内部,您可以使用解码后的数组初始化列表.基本上,改变

You are almost there. Inside the initializer, you can initialize the list using the decoded array. Basically, change

tags = try container.decode(List<Tag>.self, forKey: .tags)   // this is problem.

let tagsArray = try container.decode([Tag].self, forKey: .tags)   
tags = List(tagsArray) // Now you are good

正如注释中指出的,List构造函数不再像这样

As pointed out in the comments the List constructor no longer works like this

您现在要:

tags.append(objectsIn: tagsArray)

这篇关于如何将列表类型与Codable结合使用? (RealmSwift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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