[swift-evolution] Allow protocol vars to match derived types

Slava Pestov spestov at apple.com
Mon Mar 7 18:43:08 CST 2016


> On Mar 7, 2016, at 8:12 AM, Mark Anders via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Consider the following (you can paste it in a Playground to see the error):
> 
> class Node { }
> class Containable : Node{}
> 
> protocol Refers {
>     var to : Node {get}
> }
> 
> class Link : Refers {
>     var to : Node
>     init(n : Node) {
>         to = n
>     }
> }
> 
> class Contains : Refers {
>     var to : Containable
>     init(c : Containable) {
>         to = c
>     }
> }

You can use an associated type for this instead,

protocol Refers {
	associatedtype NodeType
	var to: NodeType { get }
}

I agree that your example should work -- the rules for patching method overrides and protocol witnesses are more stringent than they need to be. There's an interesting engineering challenge in generalizing the logic and also cleaning it up to share as much code as possible with the subtype matching code in the constraint solver.

Slava

> 
> This currently does not work because it seems that to adopt a protocol, the type of protocol var must match exactly.
> 
> It would be great if objects could be said to adopt a protocol if the type of the var is the type or a derived type.  
> This would allow me to treat the structure in a type safe way (i.e. only a Containable can have a Contains relationship), 
> while me to have a set of Refers and iterate through each Node.
> 
> Is there a reason why the type must match exactly?  Or could protocols be enhanced to to allow matching
> derived types, similar to assignment and func parameter rules?  
> 
> 
> Mark
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160307/e1cb2cb1/attachment.html>


More information about the swift-evolution mailing list