Using Self as generic parameter

大兔子大兔子 提交于 2021-02-11 13:41:37

问题


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:

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.

Is there any solution to fix this code?


回答1:


You can achieve this by creating a protocol that UIView and in turn all subclasses will adopt:

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


来源:https://stackoverflow.com/questions/36965262/using-self-as-generic-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!