As matte already explained, you cannot define an initializer that is limited to types that implement the protocol. Alternatively, you can instead define a global function:
public protocol Nameable { static func entityName() -> String } func createInstance<T : NSManagedObject where T: Nameable>(type : T.Type, context : NSManagedObjectContext) -> T { let entity = NSEntityDescription.entityForName(T.entityName(), inManagedObjectContext: context)! return T(entity: entity, insertIntoManagedObjectContext: context) }
which is then used as
let obj = createInstance(Entity.self, context)
You can avoid an extra type parameter if you define a method
func createInstance<T : NSManagedObject where T: Nameable>(context : NSManagedObjectContext) -> T { ... }
and use it as
let obj : Entity = createInstance(context)
or
let obj = createInstance(context) as Entity
where the type is now inferred from the context.
Martin r
source share