我的类有一个属性[String],我想使用Codable和Realm .

JSON是

{
    "name": "name",
    "title": "title",
    "pictureList": [ 
        "String 1",
        "String 2",
        "String 3"
     ]
}

class

class News: Object, Decodable{
    @objc dynamic var name: String!
    @objc dynamic var title: String!

    private enum CodingKeys: String, CodingKey {
        case name, title       
    }
}

它可以像这样工作another solution

但是这样我必须在func init(from decoder: ) throws 中编写一些像 name = try container.decode(Type, forKey) 这样的代码

有没有办法在没有func init(from decoder: ) throws 的情况下达到目标,只是让它自动解码 .

我的假设是添加一个像 Picture 这样的类

class News: Object, Decodable{
    @objc dynamic var name: String!
    @objc dynamic var title: String!

    @objc dynamic var pictureList: Picture

    class Picture: Object, Decodable {    
        var pictureList: [String]!

        private enum CodingKeys: String, CodingKey {
            case pictureList
        }
        public required init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            pictureList = try container.decodeIfPresent([String].self, forKey: .pictureList) ?? [""]
        }
    }
}

但我无法正确完成它 .

谢谢你的帮助 .