[swift-evolution] Enhanced existential types proposal discussion

Charles Srstka cocoadev at charlessoft.com
Sun May 29 17:13:10 CDT 2016

Forgive me if this has already come up, but since we’re talking about fixing generics, I wonder if there is any solution in the pipeline for this problem:


protocol P { func foo() }
struct S: P { func foo() { print("foo") } }

func doSomething<C: CollectionType where C.Generator.Element: P>(c: C) {
	for each in c {

let arr: [P] = [S()]

doSomething(arr) // error: cannot invoke 'doSomething' with an argument list of type '([P])’


Why is this an error? The whole definition of [P] is basically an array of things that conform to P. Isn’t that exactly what “where Element: P” is asking for?

Changing Element: P to Element == P solves this particular issue, of course, but then passing something like [S] to the array will fail. The result is that you need to write two functions, and either have one eat the performance cost of constructing a new array that has the correct static type to pass to the other (since, unlike arrays, I can’t figure out a way to convert “Collection where Element: P” into “Collection where Element == P” with a simple cast), or just fill it with the dreaded copy-paste code. Neither seems ideal.


More information about the swift-evolution mailing list