1
votes

I would like to write a function that takes an array of objects conforming to a given protocol. I wrote the following Playground code:

protocol Request {}

struct RequestA: Request {}
struct RequestB: Request {}

func execute<T: Request>(requests: [T]) {}

let requests: [Request] = [RequestA(), RequestB()]

execute(requests: requests)

However, on the last line I receive this error: "Value of protocol type 'Request' cannot conform to 'Request'; only struct/enum/class types can conform to protocols".

I believe that this error is happening because the function expects an array of objects conforming to the protocol, not an array of the protocols, but I am lost on how to do this another way.

Can someone help sort this out?

Thanks in advance!

2
You just don't need the generic type T. Change your function to this func execute(requests: [Request]) {} - gcharita
Do you really need to mix different type of objects in the same collection? Note that using a protocol as the element type only the properties required by the protocol will be accessible inside that method. - Leo Dabus

2 Answers

1
votes
func execute(requests: [Request]) {}
1
votes

As others have said you want to have func execute(requests: [Request]) {} in this case.

The reasoning is that func execute<T: Request>(requests: [T]) {} as a generic function is saying you want a concrete known type T that conforms to the Request protocol.

The change to [Request] from [T] lets you have an array of any type that conforms to Request instead of an array of one type that conforms.