我有一个带有用 Objective-C 编写的工厂方法的基类。(一些库)
@interface Base : NSObject
@property(nonatomic, strong) NSString *content;
+ (instancetype)baseWithContent:(NSString *)content;
@end
//==================
@implementation Base
+ (instancetype)baseWithContent:(NSString *)content {
Base* base = [[Base alloc]init];
base.content = content;
return base;
}
@end
然后我在 swift 中对其进行子类化并将其转换为 AnyObject。(忽略 Bridging-Header 部分)
class Child: Base {}
var c = Child(content: "Child")
print("before casting", type(of:c))
print("after casting", type(of:c as AnyObject))
得到这个奇怪的结果,它在施法后变成了一个基地。
before casting Optional<Child>
after casting Base
实际上,如果我使用指定的初始化器来覆盖 objective-c 的生成便利初始化器,我会得到正确的结果。
class Child: Base {
init?(content:String) {
super.init()
self.content = content
}
}
before casting Optional<Child>
after casting Child
我做错了吗?谢谢回答。 我正在使用 Xcode 版本 8.1 (8B62) 和 Swift 3.0.1
最佳答案
您在 Obj-C 中的工厂方法实现是错误的。它总是创建 Base
的实例。要修复它:
+ (instancetype)baseWithContent:(NSString *)content {
Base *base = [[self alloc] init]; //self instead of Base
base.content = content;
return base;
}
基本上,您的工厂方法实现与其返回类型不匹配,结果是 Swift 中的类型问题,因为 Swift 信任类型声明。
关于objective-c - 在 Swift 中使用工厂方法子类化 Objective-C 类,泛型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41106712/