如何在Swift中创建通用便利初始化器? [英] How to create generic convenience initializer in Swift?
问题描述
我正在处理Swift中的泛型.我已经扩展到NSManagedObject
类,并想创建初始化器,该初始化器仅可用于实现我定义的某些协议的类.现在,我有类似下面的内容,但是它不起作用,甚至无法编译.您能帮我使它正常工作吗?
I'm tackling with generics in Swift. I've got extension to NSManagedObject
class and wanted to create initializer which is only available for classes which implements some protocol I defined. Now I've got something like below but this is not working and even not compiling. Could you help me make it working?
public extension NSManagedObject {
public convenience init<Self: Nameable>(context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName(Self.entityName(), inManagedObjectContext: context)!
self.init(entity: entity, insertIntoManagedObjectContext: context)
}
}
public protocol Nameable {
static func entityName() -> String
}
Xcode说:函数签名中未使用通用参数'Self'."
Xcode says: "Generic parameter 'Self' is not used in function signature".
推荐答案
正如matt所述,您不能定义一个初始化器 仅限于实现协议的类型.或者,你 可以改为定义全局函数:
As matt already explained, you cannot define an initializer which is restricted to types implementing a protocol. Alternatively, you could define a global function instead:
public protocol Nameable {
static func entityName() -> String
}
func createInstance<T : NSManagedObject>(type : T.Type, context : NSManagedObjectContext) -> T where T: Nameable {
let entity = NSEntityDescription.entity(forEntityName: T.entityName(), in: context)!
return T(entity: entity, insertInto: context)
}
然后用作
let obj = createInstance(Entity.self, context)
如果您定义方法,则可以避免使用其他类型参数
You can avoid the additional type parameter if you define the method as
func createInstance<T : NSManagedObject>(context : NSManagedObjectContext) -> T where T: Nameable { ... }
并将其用作
let obj : Entity = createInstance(context)
或
let obj = createInstance(context) as Entity
现在从上下文中推断出类型.
where the type is now inferred from the context.
这篇关于如何在Swift中创建通用便利初始化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!