How to define an array of objects matching the protocol?

Given:

protocol MyProtocol { typealias T var abc: T { get } } 

And the class implementing MyProtocol:

 class XYZ: MyProtocol { typealias T = SomeObject var abc: T { /* Implementation */ } } 

How to define an array of objects matching MyProtocol ?

 var list = [MyProtocol]() 

Gives (along with a ton SourceKit error) the following error:

 Protocol 'MyProtocol' can only be used as a generic constraint because it has Self or associated type requirements 

Although typing is actually defined in MyProtocol .

Is there a way to have a list of objects that conform to the AND protocol with a common restriction?

+5
source share
1 answer

The problem is to use common code for protocols, type aliases. This sounds strange, but if you define a type alias, you cannot use the protocol as a type, which means you cannot declare a variable of this protocol type, function parameter, etc. And you cannot use it as a generic array object.

As the bugs say, the only use you can make of it is a general limitation (for example, in class Test<T:ProtocolWithAlias> ).

To prove this, simply remove typealias from your protocol (note, this is just to prove, this is not a solution):

 protocol MyProtocol { var abc: Int { get } } 

and modify the rest of your sample code accordingly:

 class XYZ: MyProtocol { var abc: Int { return 32 } } var list = [MyProtocol]() 

You will notice that it works.

You are probably more interested in how to solve this problem. I can't come up with anything elegant solution, just the following 2:

  • remove the message types from the protocol and replace T with AnyObject (ugly solution !!)
  • turn the protocol into a class (but this is not a solution that works in all cases)

but, as you can object, I do not like any of them. The only thing I can offer is to rethink your design and find out if you can use a different method (i.e. Do not use a type protocol) to achieve the same result.

+3
source

Source: https://habr.com/ru/post/1205419/


All Articles