I'm trying to instantiate an object with a specific method that returns a subclass by casting. And I can only pass the class type by name (string). But the compiler is complaining that it's not a type.
guard let entityClass = NSClassFromString(entity.rawValue) else {
preconditionedFailure("Cannot find entity with name \(entity.rawValue)")
}
let obj = NSEntityDescription.insertNewObjectForEntityForName(entity.rawValue, inManagedObjectContext: moc) as? entityClass
The compiler complains that entityClass is not a type. I know that it's an optional, but even if I unwrap it with ! the compiler still doesn't see it as a type even though NSClassFromString returns Optional(AnyClass).
Edit: I can't really find a solution in the other thread. The compiler is showing at error at the cast:
let obj = NSEntityDescription.insertNewObjectForEntityForName(entity.rawValue, inManagedObjectContext: moc) as? entityClass
"entityClass is not a type."
So can someone explain why the casting does not work even though entityClass is in fact an Optional(AnyClass)?