在Swift中返回实例类型 [英] Return instancetype in Swift
问题描述
我正在尝试进行此扩展:
I'm trying to make this extension:
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
}
}
但是我得到了编译错误:
But I get compile error:
错误:无法将类型为'UIViewController'的返回表达式转换为 返回类型"Self"
error: cannot convert return expression of type 'UIViewController' to return type 'Self'
有可能吗?我也想把它设为init(storyboardName: String, storyboardId: String)
Is it possible? Also I want to make it as init(storyboardName: String, storyboardId: String)
推荐答案
Similar as in Using 'self' in class extension functions in Swift, you can define a generic helper method which infers the type of self from the calling context:
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
.
compiles, and the type is inferred as MyViewController
.
更新迅速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
的另一种可能的解决方案:
Another possible solution, using 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中返回实例类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!