[swift-evolution] subprotocol as type when super protocol has an associated type

Benjamin Spratling bspratling at mac.com
Sat Jun 24 12:50:30 CDT 2017


I’m running into trouble using protocols as types when they have an associated type.  I understand the restriction of using a protocol with an associated type only as a generic constraint, since our down-casting syntax has no way of checking the associated types.  However, if I’m considering whether an instance conforms to a sub protocol, which introduces no additional associated types itself, when the instance is already known to conform to the super-protocol which introduces the associated type, I believe such behavior is well-defined, and should be supported.  So, I’m asking for help to put together a proposal to get this added.

Here’s an example:
3 protocols, one base Protocol which declares an associated type.
And 2 sub-protocols.

protocol A {
	associatedType V
}

protocol B : A {
	func someFunction<V>(V?)->String
}

protocol C : B {
	func someOtherFunction<V>()->V?
}

Note that the sub protocols do not add additional associated types.

When I want to use these protocols, using the base protocol as a generic constraint works fine.

class M {
	func doSomething<P, V>(a:P, completion:@escaping(V?)->()) where P : A, V==P.V {
		if let c = a as? C {
			c.someOtherFunction(…)
			… more code
		} else if let b = a as? B {
			b.someFunction(…)
			… more code
		}
	}
}

However, when I try to check whether the instance conforms to either of the sub-protocols, I get an error, saying protocols with associated types can only be used as generic constraints.

I believe that in this case, since the sub-protocols do not add any additional associated types, this code should be well-defined, and compilable.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170624/f1daae33/attachment.html>


More information about the swift-evolution mailing list