只能返回,不能分配,自我? [英] Can only return, not assign, Self?
问题描述
考虑此模式
extension UIViewController
{
class func make(sb: String, id: String) -> Self
{
return helper(sb:sb, id:id)
}
private class func helper<T>(sb: String,id: String) -> T
{
let s = UIStoryboard(name: storyboardName, bundle: nil)
let c = s.instantiateViewControllerWithIdentifier(id) as! T
return c
}
}
效果很好,所以
let s = SomeViewControllerClass.make( ... )
实际上,
返回子类"SomeViewControllerClass". (不仅仅是UIViewController.)
does in fact return the subclass "SomeViewControllerClass". (Not just a UIViewController.)
没关系,
在make
中说您要进行一些设置:
say in make
you want to do some setup:
class func make(sb: String, id: String) -> Self
{
let h = helper(sb:sb, id:id)
// some setup, m.view = blah etc
return h
}
实际上看来您无法做到这一点.
你只能
return helper(sb:sb, id:id)
你不能
let h = helper(sb:sb, id:id)
return h
有解决方案吗?
推荐答案
当然有解决方案.这正是helper
函数的作用.
Of course there is a solution. That's exactly what the helper
function is doing.
为什么不将代码放入helper
?
要调用helper
这是一种通用类型,您必须以某种方式指定该类型,例如
To invoke helper
, which is a generic type, you have to specify the type somehow, e.g.
let h: Self = helper(...)
或
let h = helper(...) as Self
,但是这些表达式都不实际接受Self
.因此,您需要根据返回值-> Self
推断类型.这就是return
是唯一起作用的原因.
but neither of those expressions would actually accept Self
. Therefore, you need to infer the type from the return value -> Self
. That's why return
is the only thing that works.
还请注意,您可以使用 second 辅助功能.
Also note that you can use a second helper function.
class func make(sb: String, id: String) -> Self {
let instance = helper2(sb: sb, id: id)
return instance
}
class func helper2(sb: String, id: String) -> Self {
return helper(sb:sb, id:id)
}
这篇关于只能返回,不能分配,自我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!