[swift-users] make a static/class method return type be the subclass it is called with

davelist at mac.com davelist at mac.com
Thu Jan 5 09:47:28 CST 2017

Is there a way to make a static or class method specify the return type be the actual class it is called with?

The example code below using protocols/extensions mostly works (the type is [Event.Entity] not [Event] but it seems to work.

If I try to make DDRCoreData a base class and Event subclass it, I'm only able to get the return type to be [DDRCoreData], not [Event] when I call it with Event.items(in: moc)

Here is the code that mostly works using protocols. Is there a better way to do this?

protocol DDRCoreData {
    associatedtype Entity: NSManagedObject

    static func items(in context: NSManagedObjectContext, matching predicate: NSPredicate?, sortedBy sorters: [NSSortDescriptor]?) -> [Entity]

extension DDRCoreData {
    static func items(in context: NSManagedObjectContext, matching predicate: NSPredicate? = nil, sortedBy sorters: [NSSortDescriptor]? = nil) -> [Entity] {
        var items: [Entity] = []
        context.performAndWait {
            let fetchRequest: NSFetchRequest<Entity> = Entity.fetchRequest() as! NSFetchRequest<Entity>
            fetchRequest.predicate = predicate
            fetchRequest.sortDescriptors = sorters
            do {
                items = try fetchRequest.execute() as [Entity]
            } catch {

        return items

public class Event: NSManagedObject {


extension Event: DDRCoreData {
    typealias Entity = Event

// compiler says items is of type [Event.Entity]
let items = Event.items(in: controller.managedObjectContext!)

Dave Reed

More information about the swift-users mailing list