在Swift中返回instancetype

前端之家收集整理的这篇文章主要介绍了在Swift中返回instancetype前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图做这个扩展:
extension UIViewController
{
    class func initialize(storyboardName: String,storyboardId: String) -> Self
    {
        let storyboad = UIStoryboard(name: storyboardName,bundle: nil)
        let controller = storyboad.instantiateViewControllerWithIdentifier(storyboardId) as! Self

        return controller
    }
}

但我得到编译错误

error: cannot convert return expression of type ‘UIViewController’ to
return type ‘Self’

可能吗?我也想做为init(storyboardName:String,storyboardId:String)

类似于 Using ‘self’ in class extension functions in Swift,您可以定义一个通用辅助方法,从调用上下文中推断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,bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: storyboardId) as! T
        return controller
    }
}
原文链接:https://www.f2er.com/swift/320757.html

猜你在找的Swift相关文章