使用Self作为通用参数

时间:2016-05-01 09:48:34

标签: 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 the result of a method in a class

有没有解决方法来修复此代码?

1 个答案:

答案 0 :(得分:3)

您可以通过创建UIView以及所有子类将采用的协议来实现此目的:

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