Daniel Thompson Daniel Thompson - 1 month ago 6
iOS Question

iOS Cannot assign value of type NSManagedObject to type 'Journal' (an entity)

I am trying to take a single entity from an array of NSManagedObjects

var journals = [NSManagedObject]()
and display it on a details page. I currently do that by declaring a variable on the destination controller when a segue is prepared from a didSelectRow action:

let indexPath = tableView.indexPath(for: (sender as! UITableViewCell))
controller.journalToDisplay = journals[indexPath!.row]


In the display controller I don't have much set up yet, just this delaration:

var journalToDisplay: Journal?


which throws the error:

Cannot assign value of type 'NSManagedObject' to type 'Journal?'


Isn't journal just an NSManagedObject anyway in this case? I tried using something like:

var journalToDisplay: NSManagedObject as! Journal


But that doesn't seem to be the right way.

Answer

Arrays do not implicitly know the types of the objects contained within them, so the compiler can't assign custom classes without explicitly casting the object you get from indexing the array.

Cast journals[indexPath!.row] to a Journal object so the compiler knows to treat it as such.