[swift-evolution] protocol can only be used as a generic constraint because it has Self or associated type requirements

Paul Cantrell cantrell at pobox.com
Mon Dec 14 01:03:43 CST 2015


> On Dec 13, 2015, at 11:56 PM, Dave Abrahams via swift-evolution <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?

Cheers, P

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


More information about the swift-evolution mailing list