Problem with associatedtype in a protocol - "Member '<method>' cannot be used on value of type 'any <protocol>';

I am having a problem trying to resolve a problem with an associated type in a protocol.

Here is the code stripped down to minimum for demonstration

protocol Protocol1
{
    associatedtype DataItem
    func protocolMethod(item : DataItem)
}

protocol Protocol2 {
    associatedtype AType1: Hashable
    //...
}

class Class1<Type1: Protocol2>: NSObject
{
    
    typealias Item = Type1.AType1
    
    var delegate : (any Protocol1)?
     
    private func method1(item: Item)
    {
        delegate?.protocolMethod(item : item)  //ERROR HERE
    }
}

The error occurring at "ERROR HERE" is:

Member 'protocolMethod' cannot be used on value of type 'any Protocol1'; consider using a generic constraint instead

This all works if the item parameter is not defined on protocolMethod (and its invocation where the error occurs). And I think I get why it's happening, that it can't determine the type of item in the invocation. Is there a way to accomplish this? I have played with it quite a bit with generic params, etc. but still can't find the right formula to make it work. Am I just asking too much from Swift in this case?

  • Read https://www.swiftbysundell.com/articles/referencing-generic-protocols-with-some-and-any-keywords/

Add a Comment