[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
Sun Dec 13 23:56:51 CST 2015


> On Dec 13, 2015, at 3:55 PM, Marc Knaup via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hey guys,
> 
> I'm looking at Swift 3.0's goal to improve generics.
> 
> 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?
}
  
> Simple examples:
> var list = [Hashable]()
> var hashable: Hashable = 2
> 
> Right now all we get is
> protocol 'Hashable' can only be used as a generic constraint because it has Self or associated type requirements


In this case it's "self requirements" inherited from Equatable that make instances of Hashable impossible.
That said, providing for sets/dictionaries of heterogeneous values is a problem we're interested in solving in the standard library.

-Dave



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


More information about the swift-evolution mailing list