我有简单的通用类:
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/