0

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)?

u84six
  • 4,604
  • 6
  • 38
  • 65
  • Possible duplicate of [Swift language NSClassFromString](http://stackoverflow.com/questions/24030814/swift-language-nsclassfromstring) – rickster Mar 31 '16 at 18:09
  • I don't think that will work because the compiler wants a literal type name. What you're attempting is similar to `var obj: entityClass`, which will also fail with a syntax error. If you get your object without trying a cast, what problem do you have? – Phillip Mills Mar 31 '16 at 19:59

0 Answers0