Search code examples
swiftgenericsprotocols

Pass an array of protocol conforming objects to function


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!


Solution

  • 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.