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/39107658/

相关文章:

swift - 快速比较两个结构的值

objective-c - 如何在 NSViewController.transition 期间将 NSViewController 固定到 NSPopover 的顶部?

ios - 在解析 JSON 数据期间在 UITableView 中滚动时卡住

ios - 如何使应用角标(Badge)编号为0? (使用解析和快速)

swift - Google Speech to Text iOS 应用示例 : could not build module 'googleapis'

ios - 删除 SwiftUI 表单填充

swift - 从 NSData 中获取字节并将结果放入字符串中

swift - 如何检测内存泄漏 <Allocated Prior To Attach>?

swift - 如何在 Swift 中保存十六进制编码的字符串

ios - MapKit 覆盖不出现