Wieczorny Wieczorny - 7 months ago 18
Swift Question

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
:

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?

Answer

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