ObjectMapper
을 사용하여 Swift 3에서 프로젝트를 개발하고 있으며 동일한 코드를 사용하는 많은 함수가 있습니다.ObjectMapper 및 swift를 사용하여 JSON을 Object에 매핑하는 함수 일반화
변환을 수행하는 기능은 이것이다 : 내가 인수로 카테고리 (매퍼)를 전달하려는
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)
}
}
}
그리고, 그래서 함수에 클래스 유형의 모든 유형을 통과하고 하나 개의 기능을 사용할 수 있습니다 일을하기 위해서는 다음과 같을 것이다 :
func convertObjects (response:[[String : Any]], type: Type) {
let jsonResponse = Mapper<Type>().mapArray(JSONArray: response)
...
I've가 많이 있지만 결과없이 생각했는데, ¿ 누구도 날이 달성 도와 드릴까요?
는 편집 :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)
답장을 보내 주셔서 감사합니다. @ Robob 함수 내에서 매개 변수를 사용하고 BaseMappable 프로토콜을 어떻게 준수합니까? FUNC의 convertCategories (응답 : [[문자열 : 어떤]], 유형 : 유형) { 할 jsonResponse = 매퍼 () .mapArray (JSONArray : 응답) .... 내가 없다는 오류가 유형이 BaseMappable 프로토콜을 따르지 않습니다 –
적합성이 필요한 경우 유형 매개 변수 (': BaseMappable')의 요구 사항으로 포함하십시오. –
매력처럼 작동했습니다. @Rob에게 감사드립니다. –