首页 文章

使用Swift中的工厂方法对Objective-C类进行子类化,泛型不起作用

提问于
浏览
1

我有一个Base类,其中包含一个用Objective-C编写的工厂方法 . (某些lib)

@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))

得到这个奇怪的结果 it become a Base after casting.

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

1 回答

  • 1

    Obj-C中的工厂方法实现是错误的 . 它始终创建 Base 的实例 . 要解决这个问题:

    + (instancetype)baseWithContent:(NSString *)content {
        Base *base = [[self alloc] init]; //self instead of Base
        base.content = content;
        return base;
    }
    

    基本上,您的工厂方法实现与其返回类型不匹配,结果是Swift中的类型问题,因为Swift信任类型声明 .

相关问题