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

标签 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
    }
}

现在 if (topLevelObject is self) { 是错误的,因为“‘是’之后的预期类型”。在那之后我所做的尝试表明了很多我对 Swift 类型系统不了解的地方。

  • if (topLevelObject is Self) {
  • if(topLevelObject 是 self.dynamicType){
  • if (topLevelObject is self.self) {
  • 一百万个其他变体 not even wrong .

欢迎任何见解。

最佳答案

使用来自 How can I create instances of managed object subclasses in a NSManagedObject Swift extension? 的方法 你可以定义一个通用的辅助方法,它从调用上下文中推断出 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
    }
}

这在我的快速测试中按预期编译和工作。如果 MyCustomView 是您的 UIView 子类

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

给你一个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
    }
}

关于swift - 在 Swift 的类扩展函数中使用 'self',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31165535/

相关文章:

ios - 在 iOS 中,使字体大小适用于所有设备大小的最佳做法是什么?

ios - 在 2 个 View Controller 上显示 View

ios - 我无法使用此代码从本地主机获取数据。请帮我。我得到零

swift - 如何将图像放入由 Kingfisher 缓存下载的数组中?

ios - 如何仅在第一次显示 View Controller 时触发 viewDidAppear 中的操作?

swift - 检测 UIKIt for Mac 的应用程序最小化事件?

ios - 如何阻止 UITableView 重复使用图像单元格数据?

ios - 从 Application Support Directory 中的 plist 中读取翻译

ios - RNCryptor 无法在 iOS 中解密

swift - 如何在Swift中编写可测试的代码