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