[swift-dev] Array with associatedtype protocol pattern

Brent Royal-Gordon brent at architechies.com
Fri Jul 15 01:47:12 CDT 2016

> On Jul 13, 2016, at 11:23 AM, 4 bottiglie g via swift-dev <swift-dev at swift.org> wrote:
> Hi, i have asked the same question :
> Here: https://forums.developer.apple.com/message/153781#153781
> And here : http://stackoverflow.com/questions/38281800/array-with-associatedtype-protocol
> But it seams like swift doesn’t have generic protocols arrays. I am asking here as a last resource if it can be done yet or there is a better design. 

The answer here is the same as the answer you've gotten from those other excellent resources.

Here's the issue: Imagine that Swift supported this feature. You write this line of code:

	let event0 = events[0]
	let event1 = events[1]

Is this code valid? Well, who knows? `event0` and `event1` might have different Interval types, or might not.

Java's type system does not try to protect you from this kind of mistake; Swift's does. Unfortunately, it's not yet expressive enough to describe the types involved. Consider this snippet:

	let event = events[0]
	let interval = event.interval

What's the type of `interval`? There's no way you can know for sure, really. All you can really say is "whatever the `IntervalType` of `event` is".

There are proposals in the works to actually allow you to say `event.IntervalType` as a type, but unfortunately they won't make Swift 3. Until that feature is added, you have three options:

1. Fake that intended future Swift feature by writing `AnyInterval` and `AnyEvent` type-erasing wrappers.
2. Halfway fake it by writing an `AnyEvent<IntervalType>` type-erasing wrapper.
3. Remove the associated type and require that any `Event` work with any `Interval` (or make `Interval` a concrete type).

Brent Royal-Gordon

More information about the swift-dev mailing list