Reputation: 7225
I'm trying to create an instance of a class which is returned from a function. Here is a playground script (that doesn't work) to explain what I would like:
import UIKit
import CoreData
class MyModel: NSManagedObject {
}
class A {
func modelClass() -> NSManagedObject {
return NSManagedObject.self
}
func doSomething() {
// create an instance from modelClass()
let instance = self.modelClass()
// I need this:
// let instance = NSManagedObject()
}
}
class B : A {
override func modelClass() -> NSManagedObject {
return MyModel.self
}
}
let a = A()
a.doSomething()
So..
A
class, I want doSomething
to be able to create an instance of NSManagedObject
and...B
class, I want doSomething
to be able to create an instance of MyModel
.Upvotes: 1
Views: 1734
Reputation: 2995
You were almost there. modelClass(and the modelClass override in B) should return:
NSManagedObject.Type
i.e.
func modelClass() -> NSManagedObject.Type {
Upvotes: 2