json - 使用 ObjectMapper 和 swift 3 通用化将 JSON 映射到对象的函数

标签 json swift swift3 objectmapper generalization

我正在使用 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)
        }
    }

}

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

    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)

最佳答案

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

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需要专门针对要转换的每种类型,这需要声明类型参数 ( <Type> )。

关于json - 使用 ObjectMapper 和 swift 3 通用化将 JSON 映射到对象的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136879/

相关文章:

macos - 添加到父 View 时,以编程方式创建的 NSView 不会出现

swift 3 : Return from initializer error

ios - swift 3 | Xcode 8 datePicker 更新 UItextField

ios - 参数标签 '(URL:)' 与任何可用的重载都不匹配

android - 从json格式数据中获取字符串

ios - 在 UINavigationController 中嵌入 Material CardTableView

javascript - 将 PHP JSON 字符串转换为有效的 json

ios - 将 CMSampleBuffer 转换为 UIImage

json - Google Chrome 60.0.3112.90 VueJS response.data 错误

python - 向 URL 添加 2 个不同的参数并返回自定义响应