Search code examples
swiftgenericscore-data

Generic parameter 'T' could not be inferred for 'Optional<Array<_>>'


I'm getting this error

Cannot convert value of type 'Optional<Array<_>>' to specified type '[FoodEntity]'. Generic parameter 'T' could not be inferred

 func fetch<T:NSFetchRequestResult>(entityName:String) throws -> [T] {
      
        let request = NSFetchRequest<T>(entityName: entityName)
        
        let entities = try container.viewContext.fetch(request)
        
        return entities
        
    }

but I have the type in the call [FoodEntity]

    let foodArray:[FoodEntity] = try PersistenceController.shared.fetch(entityName: "FoodEntity")

Solution

  • Your generic type should extend NSManagedObject

    func fetch<T:NSManagedObject>(entityName:String) ...