[swift-evolution] TreeLiteralConvertible

John McCall rjmccall at apple.com
Thu Apr 14 15:36:37 CDT 2016


> On Apr 14, 2016, at 1:34 PM, Milos Rankovic <milos at milos-and-slavica.net> wrote:
> Hi John,
> 
>> On 14 Apr 2016, at 21:09, John McCall <rjmccall at apple.com <mailto:rjmccall at apple.com>> wrote:
>> 
>> I mean, you could just make your Tree type implement all the individual literal-convertible protocols.
> 
> It does sound like something like that should be doable, but it isn’t. The literal-convertible protocols only require one initialiser, but you need two: one that lifts leaf values to Self and the other that actually takes Self elements (it is this last one that provides for recursion). In other words, we’d need to overload our conformance:
> 
> extension Tree : ArrayLiteralConvertible { // error: does not conform!
> 	init(arrayLiteral elements: Tree...) {
> 		self = .Branches(elements)
> 	}
> 	init(arrayLiteral elements: Value...) {
> 		if elements.count == 1 { self = .Leaf(elements[0]) }
> 		else { self = .Branches(elements.map{ .Leaf($0) }) }
> 	}
> }
> 
> But you can only conform in one or the other way, but not both! Therefore, for trees, we need something like:
> 
> protocol TreeLiteralConvertible {
> 	associatedtype LeafValue
> 	init(literal: Self.LeafValue...)
> 	init(literal: Self...)
> }

No, you just need Tree to conform to both ArrayLiteralConvertible and IntegerLiteralConvertible, and it implements the latter by building a Value out of it.

This would be easily done with conditional conformance; as it is, you'll simply have to make your Tree less generic, e.g. by always requiring Value to be IntegerLiteralConvertible.  Of course, this would not be a problem for a JSON tree, which would not be generic at all.

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


More information about the swift-evolution mailing list