In objc I have created extension of NSManagedObject
for creating objects. Now all subclasses can use it to create objects of its own type. I have tried something similar in swift, but quite as I would like, by using generics.
extension NSManagedObject {
// MARK: - Creation Methods
class func create<T: NSManagedObject>(in context: NSManagedObjectContext) -> T {
let entity = NSEntityDescription.entity(forEntityName: T.description(), in: context)!
return T(entity: entity, insertInto: context)
}
}
While in Person
class which is subclass of NSManagedObject
, I can call it like:
let person = Person.create(context)
person will be NSManagedObject
type, and I will have to cast it to Person
, to access properties like name, phone etc...
I would like to somehow avoid this and make method create
return instancetype
of sorts, but I am unsure how to do this?