我正在尝试进行此扩展:
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
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到编译错误:
错误:无法将'UIViewController'类型的返回表达式转换为返回类型'Self'
可能吗?我也想成为init(storyboardName: String, storyboardId: String)
我希望能够从Nib中提取UIView子类的实例.
我希望能够调用MyCustomView.instantiateFromNib()并拥有MyCustomView的实例.我几乎已经准备好通过桥接头来移植我正在使用的Objective-C代码,但我想先尝试一下惯用法.那是两个小时前.
extension UIView {
class func instantiateFromNib() -> Self? {
let topLevelObjects = NSBundle.mainBundle().loadNibNamed("CustomViews", owner: nil, options: nil)
for topLevelObject in topLevelObjects {
if (topLevelObject is self) {
return topLevelObject
}
}
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
现在if (topLevelObject is self) {是错误的,因为"预期后的类型是'".我之后尝试过的东西显示了很多我对Swift类型系统不了解的东西.
if (topLevelObject is Self) {if (topLevelObject is self.dynamicType) {if (topLevelObject is self.self) {任何见解都表示赞赏.