基于类的通用返回类型 [英] Generic Return Type Based on Class

查看:55
本文介绍了基于类的通用返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个类上创建工厂方法,该方法会自动强制转换为它所在的类.

I'm trying to create factory method on a class that automatically casts to the class it's on.

extension NSObject {
    // how can I get the return type to be the current NSObject subclass
    // instead of NSObject?
    class func create() -> NSObject {
        return self.init()
    }

    // example: create(type: NSArray.self)
    class func create<T:NSObject>(type:T.Type) -> T {
        return T()
    }
}

示例二有效,但从类方法中得不到任何好处:

Example two works, but gets NO advantage from being a class method:

let result = NSArray.create(type: NSArray.self) 

但是我很希望能够拨打电话:

But I'd love to be able to just call:

let result = NSArray.create() 

无需随后投射.在Swift中有没有办法做到这一点?

without having to cast afterwards. Is there a way to do this in Swift?

推荐答案

您可以为此使用类级别的Self:

You can use the class-level Self for this:

extension NSObject {
    class func create() -> Self {
        return self.init()
    }
}

let array = NSArray.create()

但是我真的不明白为什么要这么做,因为您最好只添加一个初始化程序.

But I don't really see why you would, since you might as well just add an initializer.

这篇关于基于类的通用返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆