只能return,不能赋值,Self?
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( ... )
实际上 return 是子类 "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
。因此,您需要从 return 值 -> Self
推断类型。这就是为什么 return
是唯一有效的原因。
另请注意,您可以使用 second 辅助函数。
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)
}
考虑
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( ... )
实际上 return 是子类 "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
。因此,您需要从 return 值 -> Self
推断类型。这就是为什么 return
是唯一有效的原因。
另请注意,您可以使用 second 辅助函数。
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)
}