且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift中创建通用便利初始化器?

更新时间:2022-11-22 22:38:14

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