[swift-evolution] protocol can only be used as a generic constraint because it has Self or associated type requirements
Dave Abrahams
dabrahams at apple.com
Mon Dec 14 01:37:11 CST 2015
> On Dec 13, 2015, at 11:03 PM, Paul Cantrell <cantrell at pobox.com> wrote:
>
>> On Dec 13, 2015, at 11:56 PM, Dave Abrahams via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>
>>> On Dec 13, 2015, at 3:55 PM, Marc Knaup via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>>> Is there any info yet if and how we will be able to refer to instances of protocols that have associated types?
>>>
>>> As far as I know, this isn't a solvable problem.
>
>>>
>>> What is the difficulty in supporting this?
>>
>> Here's a simple example:
>>
>> protocol P {
>> typealias A
>> var x: A { get set }
>> }
>>
>> struct Y : P {
>> var x: Int
>> }
>>
>> struct Z : P {
>> var x: String
>> }
>>
>> func f(p1: P, p2: P) {
>> p1.x = p2.x // assigning an Int to a String?
>> }
>
> p1.x = p2.x should be a compiler error, because there’s not enough type information.
> But that shouldn’t stop a programmer from doing this:
>
> protocol P {
> typealias A
> var x: A { get set }
> var y: Int
> }
>
> struct Y : P {
> var x: Int
> var y: Int
> }
>
> struct Z : P {
> var x: String
> var y: Int
> }
>
> func maxY(p1: P, p2: P) -> Int {
> return max(p1.y, p2.y) // No problems here!
> }
>
> …right?
Ah, but then you have the situation that P doesn't conform to P (it doesn't have an x that you can access). In my opinion that is just too weird an idea to be usable.
Personally, I have always thought that protocols intended to be used as unbound existentials (not P<A: Int>, just plain P) are different beasts entirely from the kind used as generic constraints and should be explicitly declared as such—I don't think I've ever seen a protocol that is well-used in both ways; if you have counterexamples I'd love to see them. In "existential protocols," declaring an associated type or creating a self requirement would be an error at the point of declaration.
-Dave
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151213/ea54ef9b/attachment.html>
More information about the swift-evolution
mailing list