在Swift中返回实例类型

在Swift中返回实例类型,第1张

在Swift中返回实例类型

与在Swift的类扩展函数中使用’self’类似,您可以定义一个通用的辅助方法,该方法可以从调用上下文中推断出self的类型:

extension UIViewController{    class func instantiateFromStoryboard(storyboardName: String, storyboardId: String) -> Self    {        return instantiateFromStoryboardHelper(storyboardName, storyboardId: storyboardId)    }    private class func instantiateFromStoryboardHelper<T>(storyboardName: String, storyboardId: String) -> T    {        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)        let controller = storyboard.instantiateViewControllerWithIdentifier(storyboardId) as! T        return controller    }}

然后

let vc = MyViewController.instantiateFromStoryboard("name", storyboardId: "id")

进行编译,并将类型推断为

MyViewController


Swift 3 更新

extension UIViewController{    class func instantiateFromStoryboard(storyboardName: String, storyboardId: String) -> Self    {        return instantiateFromStoryboardHelper(storyboardName: storyboardName, storyboardId: storyboardId)    }    private class func instantiateFromStoryboardHelper<T>(storyboardName: String, storyboardId: String) -> T    {        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)        let controller = storyboard.instantiateViewController(withIdentifier: storyboardId) as! T        return controller    }}

另一种可能的解决方案,使用

unsafeDowncast

extension UIViewController{    class func instantiateFromStoryboard(storyboardName: String, storyboardId: String) -> Self    {        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)        let controller = storyboard.instantiateViewController(withIdentifier: storyboardId)        return unsafeDowncast(controller, to: self)    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4911732.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-12
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存