Wieczorny
Wieczorny

Reputation: 181

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?

Upvotes: 0

Views: 142

Answers (1)

sketchyTech
sketchyTech

Reputation: 5906

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

Upvotes: 3

Related Questions