相关疑难解决方法(0)

在Swift中返回instancetype

我正在尝试进行此扩展:

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)

swift swift-extensions swift2

35
推荐指数
2
解决办法
1万
查看次数

在Swift中的类扩展函数中使用'self'

我希望能够从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) {
  • 其他一百万种变化都没有错.

任何见解都表示赞赏.

swift

9
推荐指数
1
解决办法
3095
查看次数

标签 统计

swift ×2

swift-extensions ×1

swift2 ×1