I am trying to teach myself core data. I have code that works including the function below, if I hard code the result type, that will test a persistent store to see if it is empty and if so, read in data from disk and store it to persistent stores. I would like to make this function generic so I can use it for all 3 entities/classes that I have created. The problem I am unable to solve is how to create a variable that I can insert into of NSFetchRequest. If there is a better way to solve the problem I am all ears. Thank you.
func addModelValuesToContainerIfEmpty(container: NSPersistentContainer, fundName: String) { // will pass in one of three fund names
let fileName: String = "Formatted" + fundName
let entityName: String = fundName + "Entity"
let resultType: NSFetchRequestResult = String(fundName + "Entity") as! NSFetchRequestResult
do {
let request = NSFetchRequest<resultType>(entityName: entityName) // error = cannot find type 'resultType' in scope
let numRecords: Int = try container.viewContext.count(for: request)
if numRecords == 0 {
let data = GetDF(fileName: fileName)
let lastRowIndex: Int = data.shape.rows - 1
for i in 0...lastRowIndex {
let newDailyCloseEntity = VOOEntity(context: container.viewContext)
let tempDFRow: DataFrame.Row = data[row: i]
newDailyCloseEntity.date = stringDateFormatter.date(from: tempDFRow[0] as! String)
newDailyCloseEntity.close = tempDFRow[1] as! Float
do {
try container.viewContext.save()
} catch let error {
print("Error saving. \(error)")
}
} // end for loop
}
} catch {
print("Error")
}
}