【问题标题】:Generalizing a function to map JSON to Object using ObjectMapper and swift 3使用 ObjectMapper 和 swift 3 泛化将 JSON 映射到 Object 的函数
【发布时间】:2017-11-06 12:18:00
【问题描述】:

我正在使用 ObjectMapper 在 Swift 3 中开发一个项目,并且我有很多使用相同代码的功能。

进行转换的函数是这样的:

    func convertCategories (response:[[String : Any]]) {

    let jsonResponse = Mapper<Category>().mapArray(JSONArray: response )

    for item in jsonResponse!{
        print(item)
        let realm = try! Realm()
        try! realm.write {
            realm.add(item)
        }
    }

}

我想将 Category (Mapper) 作为参数传递,所以我可以将任何类型的 Class Types 传递给函数,并且只使用一个函数来完成这项工作,它看起来像这样:

    func convertObjects (response:[[String : Any]], type: Type) {

    let jsonResponse = Mapper<Type>().mapArray(JSONArray: response )

...

我尝试了很多想法,但没有结果,¿任何人都可以帮助我实现这一目标吗?

已编辑:对于所有有相同问题的人,解决方案如下:

    func convertObjects <Type: BaseMappable> (response:[[String : Any]], type: Type)
{
    let jsonResponse = Mapper<Type>().mapArray(JSONArray: response )



    for item in jsonResponse!{
        print(item)
        let realm = try! Realm()
        try! realm.write {
            realm.add(item as! Object)
        }
    }


}

调用函数是:

self.convertObjects(response: json["response"] as! [[String : Any]], type: type)

【问题讨论】:

    标签: json swift swift3 objectmapper generalization


    【解决方案1】:

    我怀疑您只是在这里遇到了语法问题。你的意思是这样的:

    func convertObjects<Type: BaseMappable>(response:[[String : Any]], type: Type)
    

    你也可以这样写(有时更易读,特别是当事情变得复杂时):

    func convertObjects<Type>(response:[[String : Any]], type: Type)
        where Type: BaseMappable {
    

    你通常会这样称呼它:

    convertObjects(response: response, type: Category.self)
    

    关键是convertObjects 需要专门用于您要转换的每种类型,这需要声明一个类型参数 (&lt;Type&gt;)。

    【讨论】:

    • 感谢您的快速回复,@Rob 我怎样才能使用函数内部的参数并且还符合 BaseMappable 协议? func convertCategories (response:[[String : Any]], type: Type) { let jsonResponse = Mapper().mapArray(JSONArray: response ) .... 我有一个错误说 Type 不是符合 BaseMappable 协议
    • 如果您需要一致性,请将其作为类型参数的要求 (: BaseMappable)。
    猜你喜欢
    • 2016-05-25
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多