ios - 使用 Self 作为泛型参数

标签 ios swift generics

我有简单的通用类:

class MyClass<T> {
    let closure: (T -> Void)

    init(closure: T -> Void) {
        self.closure = closure
    }
}

我想为 UIView 编写一个扩展,它将闭包应用于 UIView 的任何子类:

extension UIView {
    func apply(c: MyClass<Self>) -> Self {
        c.closure(self)
        return self
    }
}

但它给了我一个错误:'Self' is only available in a protocol or as a result of a method in a class

是否有解决此代码的解决方案?

最佳答案

您可以通过创建一个 UIView 和所有子类都将采用的协议(protocol)来实现这一点:

protocol View {}
extension UIView:View {}

extension View  {
    func apply(c:MyClass<Self>) -> Self {
        c.closure(self)
        return self
    }
}

let m = MyClass<UILabel>(closure: {t in})
let l = UILabel().apply(m) // UILabel returned

关于ios - 使用 Self 作为泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965262/

相关文章:

ios - 访问 WKWebView 的 AVPictureInPictureController 委托(delegate)回调

generics - Scala 泛型和数字隐式

java - Java 中泛型的访问类型

ios - 如何选择一种方法在一定秒后执行选择器?

ios - 对不同的 ViewController 具有相同操作的自定义 UIButton 类

ios - 带有 JSON 参数的多部分数据 Alamofire

ios - UISplitview Controller 在 iOS 4.3 和 5.x 中不旋转。它在 iOS 6.0 上运行良好

ios - 在 TableViewControllers 和 ViewControllers/Swift 之间切换数据

带有 Protocol.Type 的 Swift 泛型

ios - 在 Collection View 中显示三个单元格