I am using Core Data in Swift and am having trouble storing the array returned from a fetch request. I have two entities in my data model: Task and Homework. Homework's parent entity is Task. I auto generated the classes for the two entities:
Task.swift
import Foundation
import CoreData
class Task: NSManagedObject {
@NSManaged var name: String
@NSManaged var due: NSDate
@NSManaged var subject: Subject
}
Homework.swift
import Foundation
import CoreData
class Homework: Task {
}
In my view controller, in view did load, I have the following code.
var error: NSError? = nil
let fetchRequest = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Task", inManagedObjectContext: managedObjectContext)
fetchRequest.entity = entity
tasks = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as [Task]
Earlier in the view controller, I initialized tasks:
var tasks : [Task] = []
However, when I run the the application, I get the following runtime error at the line where I assign the array to tasks: fatal error: array cannot be downcast to array of derived
If I replace the assignment line with var temp = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]
, the error does not occur, but I need to save it as an array of Tasks in order to be able to use the custom classes that I generated. What am I doing wrong?