在 Swift 中返回实例类型 [英] Return instancetype in Swift
本文介绍了在 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
}
}
但是我得到编译错误:
错误:无法将UIViewController"类型的返回表达式转换为返回类型自我"
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)
推荐答案
类似于 在 Swift 的类扩展函数中使用 'self',您可以定义一个通用的辅助方法,该方法从调用上下文推断 self 的类型:
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
.
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
:
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屋!
查看全文