I’m trying to create a method to insert relationship into Core Data using Generics but I’ve problem with generics:
below there is the code that I’ve written.
Can you help me to fix it?
let lista = kanji.map{($0.kunYomi)} // let lista: [[KunYomi]]
let batchInsert2 = createBatchInsertRelationshipRequest(from: lista[0], for: KunYomi.self) // Here is the error Instance method 'createBatchInsertRelationshipRequest(from:for:)' requires that 'KunYomi' conform to 'BatchInsertable'
private func createBatchInsertRelationshipRequest<T:BatchInsertable, E:NSManagedObject>(from relationshipCollection:[T], for type:E.Type) -> NSBatchInsertRequest {
var index = 0
var total = relationshipCollection.count
let batchInsertRequest = NSBatchInsertRequest(entity: E.entity(), dictionaryHandler: { dictionary in
guard index < total else { return true }
dictionary.addEntries(from: relationshipCollection[index].dictionaryValue as [AnyHashable: Any])
index += 1
return false
})
return batchInsertRequest
}
public struct KunYomi:BatchInsertable{
public let id:Int16
public let kunYomiKanji:String
public let kunYomiKana:String
public let kunYomiRomaji:String
public let kunYomiRomaji1:String
public let idKanji:Int16
enum CodingKeys:String, CodingKey{
case id = "id"
case kunYomiKanji = "kun_yomi_kanji"
case kunYomiKana = "kun_yomi_kana"
case kunYomiRomaji = "kun_yomi_romaji"
case kunYomiRomaji1 = "kun_yomi_romaji_1"
case idKanji = "id_kanji"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = Int16( try container.decode(String.self, forKey: .id)) ?? 0
self.kunYomiKanji = try container.decode(String.self, forKey: .kunYomiKanji)
self.kunYomiKana = try container.decode(String.self, forKey: .kunYomiKana)
self.kunYomiRomaji = try container.decode(String.self, forKey: .kunYomiRomaji)
self.kunYomiRomaji1 = try container.decode(String.self, forKey: .kunYomiRomaji1)
self.idKanji = Int16( try container.decode(String.self, forKey: .idKanji)) ?? 0
}
var dictionaryValue: [String : Any] {
["id":id as Any,
"kunYomiKanji":kunYomiKanji as Any,
"kunYomiKana":kunYomiKana as Any,
"kunYomiRomaji":kunYomiRomaji as Any,
"kunYomiRomaji1":kunYomiRomaji1 as Any,
"idKanji":idKanji as Any
]
}
}
protocol BatchInsertable:Codable {
var dictionaryValue:[String:Any] { get }
}