考虑 this pattern
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。)
没关系,但是
在 make
中说你想做一些设置:
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
函数正在做的事情。
为什么不把代码放到helper
中呢?
要调用通用类型的 helper
,您必须以某种方式指定类型,例如
let h: Self = helper(...)
或
let h = helper(...) as Self
但这些表达式实际上都不会接受 Self
。因此,需要根据返回值->Self
来推断类型。这就是为什么 return
是唯一有效的原因。
另请注意,您可以使用第二个 辅助函数。
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)
}
关于swift - 只能返回,不能赋值,Self?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42161710/