0
votes

I have two protocols A and B where B inherits from A.

protocol A { }

protocol B: A { }

And I have a utility class which has function called add whose parameter should conform to the protocol A:

class Utility {
    func add<T:A>(t:T.Type,param:T){
        ....
    }
}

Then I have a test class which creates object of Utility and calls its function add which accepts a parameter of type B (class object which implements B):

class Test {
    var util: Utility

    init() {
        util = Utility()
    }

    func addItem(data:B){
        util.add(B.self,param: data) // This line produces Cannot invoke add with argument list 
    }                         // of type (B.Protocol,param:B)
}

What am I doing wrong?

1
Please simply copy and paste your code to avoid posting mistakes. - Arc676
I think your case can be simplified down to this: swiftstub.com/171514009. It seems that Swift can not handle protocol type of arguments in generic functions with constraints. Don't know (yet) if that's a bug or by-design. - 0x416e746f6e

1 Answers

0
votes

Your mistake is that you are trying to accept variable as a protocol, not the type conforming to the protocol:

func addItem(data:B){
    util.add(B.self,param: data)
} 

Which is strange, because you did it right in the Utility class. Simple fix is to do exactly the same here (using constraints):

func addItem<T: B>(data: T) {
    util.add(T.self, param: data)
}