rdougan
rdougan

Reputation: 7225

Return a class type from a function?

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..

Upvotes: 1

Views: 1734

Answers (1)

Craig Grummitt
Craig Grummitt

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

Related Questions