Swift 3のプロジェクトをObjectMapper
で開発していますが、同じコードを使用する関数がたくさんあります。ObjectMapperとswiftを使用してJSONをオブジェクトにマップする関数の一般化
変換を行う機能がこれです:私は、引数としてカテゴリー(マッパー)を渡したい
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)
すばやくお返事ありがとう@Rob関数内でこのパラメータを使用するにはどうしたらいいですか?また、BaseMappableプロトコルにも準拠していますか? FUNCのconvertCategories(応答:[文字列:任意]、タイプ:タイプ) {せjsonResponse =マッパー().mapArray(JSONArray:応答) ....私はというエラーを持っています型がBaseMappableプロトコルに準拠していません –
適合が必要な場合は、型パラメータ( ':BaseMappable')の要件として組み込みます。 –
魅力のように働いて、すべての@Robに感謝 –