Home > Net >  Is it possible to constrain `Self` to a generic parameter?
Is it possible to constrain `Self` to a generic parameter?

Time:03-03

I'm having some issues with a delegate protocol that has associated types. Currently, my implementation looks like this:

protocol Delegate: AnyObject {
    associatedtype Foo

    func doSomething(with bar: Bar<Self>) -> Foo
}

class Bar<T: Delegate> {
    weak var delegate: T?

    func makeFoo() -> T.Foo? {
        return delegate?.doSomething(with: self)
    }
}

While this works, the constraint of Bar<Self> prevents the delegate from being a non-final class. I want to say something like this:

protocol Delegate: AnyObject {
    associatedtype Foo

    func doSomething<T: Delegate>(with bar: Bar<T>) -> Foo
    where Self: T
}

However, even though T is constrained to AnyObject, it gives me the error:

Type 'Self' constrained to non-protocol, non-class type 'T'

Is there any type-safe way to allow the delegate to belong to a non-final class?

CodePudding user response:

I managed to do it using:

func doSomething<T: Delegate>(with bar: Bar<T>) -> Foo where T.Foo == Foo

It seems using T: Self does not work here and you have to add the condition for equal associated types.

  • Related