在Swift中返回instancetype
发布时间:2020-12-14 05:58:52 所属栏目:百科 来源:网络整理
导读:我试图做这个扩展: extension UIViewController{ class func initialize(storyboardName: String,storyboardId: String) - Self { let storyboad = UIStoryboard(name: storyboardName,bundle: nil) let controller = storyboad.instantiateViewControllerW
|
我试图做这个扩展:
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
}
}
但我得到编译错误:
可能吗?我也想做为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
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
