swift - 在 Swift 中返回实例类型

标签 swift swift2 swift-extensions

我正在尝试进行此扩展:

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, 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)
    }
}

关于swift - 在 Swift 中返回实例类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51809078/

相关文章:

ios - 快捷方式项目,快速操作 3D Touch swift

swift - 类型 'UIImage' 的值没有成员

ios - 对成员 Swift 3 的模糊引用

ios - 仅在符合特定协议(protocol)时才对类进行 Swift 扩展

ios - 如何在导航栏内隐藏 UISearchController

ios - Swift Facebook SDK 无法工作,出现 "Include of non-modular header..."错误

ios - 如何在 swift iOS 中编写正确的目标选择器?

swift - 为什么我的自定义类无法识别 swift 扩展? (即字符串)

ios - 一个错误? UIView 扩展中的属性

Swift 在泛型类中使用泛型函数