Swift 无法将存储库对象转换为任何要导入的对象

Swift 无法将存储库对象转换为任何要导入的对象,swift,realm,Swift,Realm,我需要将大约30000条记录的json数据集批量导入一个领域数据库 存储库对象的可解码设置: struct Repository { let xxxx:Int let xxxx:String let xxxx:String let xxxx:Int let xxxx:String let xxxx:String let xxxx:String } extension Repository : Decodable { static

我需要将大约30000条记录的json数据集批量导入一个领域数据库

存储库对象的可解码设置:

struct Repository {
    let xxxx:Int
    let xxxx:String
    let xxxx:String
    let xxxx:Int
    let xxxx:String
    let xxxx:String
    let xxxx:String
}

extension Repository : Decodable {
    static func decode(json: AnyObject) throws -> Repository {
        return try Repository(
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx"
        )
    }
}
对于领域导入,我有:

                    let config = Realm.Configuration(
                        path: utility.getDocumentsDirectory().stringByAppendingPathComponent("Meta.realm"),
                        readOnly: false)

                    let realm = try! Realm(configuration: config)

                    try! realm.write {
                        let json = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
                        let repo = try! [Repository].decode(json)

                        realm.create(Meta.self, value: repo, update: true)
                    }

问题在于,repo对象属于自定义类/对象类型,可进行解码,并且不能转换为域中值标签的任何对象。create

域要求您的对象派生自名为“object”的特殊类

您需要将结构更改为类,并确保从对象派生:

class Repository : Object {
    dynamic var xxxx:Int
    dynamic var xxxx:String
    dynamic var xxxx:String
    dynamic var xxxx:Int
    dynamic var xxxx:String
    dynamic var xxxx:String
    dynamic var xxxx:String
}

extension Repository : Decodable {
    static func decode(json: AnyObject) throws -> Repository {
        return try Repository(
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx",
            xxxx: json => "xxxx"
        )
    }
}

//现在,您应该能够将存储库对象保存到域中

不幸的是,进行上述更改会产生一系列错误。”非最终类存储库中的方法decode必须返回self以符合协议Decodable,并且不能调用类型为Repository的初始值设定项。上面的代码是per Decodable的文档,不幸的是,它没有返回对象,尽管per Realm的文档它“应该”可以工作lol。不过,你的回答确实引导了我正确的方向。我必须将结构转换为类并消除扩展。最终只是将其定义为类存储库:对象、可解码,然后创建一个初始值设定项和抛出等。这很有效:)