简体   繁体   English

在Swift 2.2中模糊地使用init

[英]Ambiguous use of init in Swift 2.2

I'm getting an "ambiguous use of init" error when building with Xcode 7.3 and Swift 2.2 在使用Xcode 7.3和Swift 2.2构建时,我得到了“模糊使用init”错误

The issue is related to two Objective-C classes and how Swift views their initializers. 该问题与两个Objective-C类以及Swift如何查看其初始化器有关。

Objc sees: Objc看到:

Superclass

@interface Foo: NSManagedObject
+(instancetype)fooWithOwner:(Owner *)owner insertIntoManagedObjectContext:(NSManagedObjectContext *)context;

Subclass 子类

@interface Bar: Foo
+(instancetype)barWithOwner:(Owner *)owner insertIntoManagedObjectContext:(NSManagedObjectContext *)context;

while Swift only sees: 而斯威夫特只看到:

init(owner: Owner!, insertIntoManagedObjectContext context: NSManagedObjectContext!)

which is causing the compiler to be unsure of which init is being called on the subclass "Bar". 这导致编译器不确定在子类“Bar”上调用哪个init。 Is there a way to specify which initializer to use when initializing the subclass? 有没有办法在初始化子类时指定使用哪个初始值设定项? I'd like to avoid refactoring the init method if possible. 如果可能的话,我想避免重构init方法。

It is due to ObjC->Swift API translation rules . 这是由于ObjC-> Swift API转换规则

You can use swift_name attribute to overwrite these rules. 您可以使用swift_name属性覆盖这些规则。

@interface Foo: NSManagedObject
+(instancetype)fooWithOwner:(Owner *)owner insertIntoManagedObjectContext:(NSManagedObjectContext *)context NS_SWIFT_NAME(foo(owner:moc:));

@interface Bar: Foo
+(instancetype)barWithOwner:(Owner *)owner insertIntoManagedObjectContext:(NSManagedObjectContext *)context NS_SWIFT_NAME(bar(owner:moc:));

Then you can call them separately in Swift code: 然后你可以在Swift代码中单独调用它们:

let foo = Bar.foo(owner: owner, moc: context)
let bar = Bar.bar(owner: owner, moc: context)

I'm not sure what's going on, btw I tried this. 我不知道发生了什么事,顺便说一句,我试过了。 In the ObjC header I added those two class methods: 在ObjC标题中,我添加了这两个类方法:

+ (id)barWithInitializer:(NSString *)className
 initializer:(SEL)initializer
    argument:(id)argument;

+ (id)fooWithInitializer:(NSString *)className
                initializer:(SEL)initializer
                   argument:(id)argument;

Then in the Swift function 然后在Swift函数中

I have tried both with no issue / interface mismatch 我试过这两个没有问题/接口不匹配

return OBJCObjectFactory.barWithInitializer(className, initializer: initializer, argument: argument) as! TBase?

return OBJCObjectFactory.fooWithInitializer(className, initializer: initializer, argument: argument) as! TBase?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM