I'm trying to understand why calling a generic function with an instance of a protocol results in a compile error. Given the following code:
public protocol MyProtocol {}
public class MyClass: MyProtocol {}
public func myFunc<T: MyProtocol>(_ foo: T) -> T {
return foo
}
public func test() {
let foo: MyClass = MyClass()
let bar: MyProtocol = foo
myFunc(foo) // ok
myFunc(bar) // compile error
}
The compiler fails thusly: cannot invoke 'myFunc' with an argument list of type '(MyProtocol)'
on the myFunc(bar)
statement.
Declaring MyProtocol
as @objc
allows the example to compile (presumably because it's causing MyProtocol to become some sort of concrete type behind the scenes, or something?).
Why is this disallowed in Swift, and is there a nicer workaround than @objc
-ifying my protocols?