Failing to use a generic function with a protocol type argument

Why does this not work, my misunderstanding or a bug?


protocol Foo {}

extension Int : Foo {}

func bar<T:Foo>( objects : [ T ] )->T?
{
  return objects.first
}

let x1 : [ Foo ]     = [ 123, 456]
let x2 : [ Int ]     = [ 345, 678 ]

bar( x1 ) // <- fails : expected an argument list of type [T]

bar( x2 ) // OK


I have an empty protocol Foo, a function which is generic on any Type which is a Foo. I've made Int conform to Foo here and can pass an Int array to the function and it works. However if I try to pass a Foo array, the compiler doesn't allow it. It took me a while to figure out it only works if I pass a concrete type which conforms to Foo and doesn't work if I pass something which is a Foo or another Protocol which extends Foo.


A protocol is a 'type' and Foo is a type conforming to Foo, so it should satisfy the generic function and be callable.

Answered by OOPer in 18531022

As clearly stated in this thread:

Extending SequenceType for elements conforming to a protocol

"the protocol type (...) doesn't conform to the protocol"


I think this behavior should be changed, but I don't know when it will.

Accepted Answer

As clearly stated in this thread:

Extending SequenceType for elements conforming to a protocol

"the protocol type (...) doesn't conform to the protocol"


I think this behavior should be changed, but I don't know when it will.

Aha - didn't see that thread - bug filed.

Failing to use a generic function with a protocol type argument
 
 
Q