Search code examples
iosswiftgenericsdelegatesretain-cycle

Creating generics with delegate protocol type


I am trying to refactor this code:

@objc protocol BaseDelegate {
    func xxx()
}

protocol DerivedDelegate: BaseDelegate {
    func yyy()
}

protocol NextDerivedDelegate: BaseDelegate {
    func zzz()
}

class BaseClass<T> {
    var delegate: T?
}

class DerivedClass: BaseClass<DerivedDelegate> {
     ....
}

class NextDerivedClass: BaseClass<NextDerivedDelegate> {
     ....
}

As you can already tell, there is a memory leak here, among other things that can go wrong. So I am trying to refactor it but to no avail. This is what I currently have:

@objc protocol BaseDelegate: AnyObject {
    func xxx()
}

protocol DerivedDelegate: BaseDelegate {
    func yyy()
}

protocol NextDerivedDelegate: BaseDelegate {
    func zzz()
}

class BaseClass<T: BaseDelegate> {
    weak var delegate: T?
}

class DerivedClass: BaseClass<DerivedDelegate> {
     ....
}

class NextDerivedClass: BaseClass<NextDerivedDelegate> {
     ....
}

But when I was tried building it, it returned this error:

Type 'any DerivedDelegate' cannot conform to 'BaseDelegate'

Even when I tried class DerivedClass: BaseClass<BaseDelegate> it returned Type 'any BaseDelegate' cannot conform to 'BaseDelegate'. Is there any way to fix this? There are a lot of these classes and delegates so changing them one by one and removing the generics should be the last thing to do if there is any other solution.

Thank you.


Solution

  • Swift protocols cannot conform to other protocols, but Objective-C protocols can.

    The code compiles if all three protocols are @objc.

    @objc 
    protocol BaseDelegate: AnyObject {
        func xxx()
    }
    
    @objc
    protocol DerivedDelegate: BaseDelegate {
        func yyy()
    }
    
    @objc
    protocol NextDerivedDelegate: BaseDelegate {
        func zzz()
    }