简体   繁体   English

使用Self作为通用参数

[英]Using Self as generic parameter

I have simple generic class: 我有简单的泛型类:

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

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

I would like to write an extension for UIView which would apply closure to any subclass of UIView : 我想编写一个扩展UIView将适用于封闭的任何子类UIView

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

But it gives me an error: 'Self' is only available in a protocol or as the result of a method in a class . 但这给了我一个错误: 'Self' is only available in a protocol or as the result of a method in a class

Is there any solution to fix this code? 有解决此代码的解决方案吗?

You can achieve this by creating a protocol that UIView and in turn all subclasses will adopt: 您可以通过创建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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM