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

rob*_*408 9 swift

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

任何见解都表示赞赏.

Mar*_*n R 18

使用方法如何在NSManagedObject Swift扩展中创建托管对象子类的实例? 您可以定义一个通用的辅助方法,它self从调用上下文中推断出类型:

extension UIView {

    class func instantiateFromNib() -> Self? {
        return instantiateFromNibHelper()
    }

    private class func instantiateFromNibHelper<T>() -> T? {
        let topLevelObjects = NSBundle.mainBundle().loadNibNamed("CustomViews", owner: nil, options: nil)

        for topLevelObject in topLevelObjects {
            if let object = topLevelObject as? T {
                return object
            }
        }
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)

这在我的快速测试中编译并按预期工作.那么如果 MyCustomView是你的UIView子类

if let customView = MyCustomView.instantiateFromNib() {
    // `customView` is a `MyCustomView`
    // ...
} else {
    // Not found in Nib file
}
Run Code Online (Sandbox Code Playgroud)

为您提供实例MyCustomView,并自动推断类型.


Swift 3更新:

extension UIView {

    class func instantiateFromNib() -> Self? {
        return instantiateFromNibHelper()
    }

    private class func instantiateFromNibHelper<T>() -> T? {
        if let topLevelObjects = Bundle.main.loadNibNamed("CustomViews", owner: nil, options: nil) {
            for topLevelObject in topLevelObjects {
                if let object = topLevelObject as? T {
                    return object
                }
            }
        }
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)