[swift-evolution] Proposal: 'T(literal)' should construct T using the appropriate literal protocol if possible

David Sweeris davesweeris at mac.com
Thu Jun 2 15:23:52 CDT 2016


> On Jun 2, 2016, at 12:57 PM, John McCall <rjmccall at apple.com> wrote:
> 
>> On Jun 2, 2016, at 10:49 AM, David Sweeris <davesweeris at mac.com <mailto:davesweeris at mac.com>> wrote:
>> I’m not entirely sure what an “expr-collection” is.
> 
> Collection literals, e.g. [x,y,z] and [a: x, b: y].
Thought so, but I wasn’t sure. Thanks for clarifying :-)

> 
>> Does your proposal mean that in this code:
>> func foo() -> Int {...}
>> var w = 0
>> var x = T(foo())
>> var y = T(w)
>> var z = T(0)
>> different initializers would be used for `x`,`y`, and `z`?
> 
> z would be initialized using the literal initializer if T conforms to that protocol, yes.
> 
>> If so, that seems a potential source of much subtler problems.
> 
> Note that this is only an issue for types that conform to the literal protocols.

Oh, I know. The crux of my concern is that while the difference between `UInt16(7)` and `7 as UInt16` is subtle, it’s not that subtle… the literal convertible syntax doesn’t even look that much like a call to init, so it shouldn’t be that surprising if explicitly calling the init function might send you down a different code path. OTOH, this proposal silently (and invisibly) rewrites an explicit call to`init(_: Int)` to `init(integerLiteral: IntegerLiteralType)`, which seems worse. Again, I don’t disagree that there’s a subtlety here, but at least with the current behavior, the unexpected behavior comes from not paying attention to syntax.

>> I don’t disagree that you’ve identified a potential source of issues, but it’s conceivable that there might be circumstances where the "semantically very different results” are desired. I can’t think of any off the top of my head, but I’m not convinced that means they don’t exist.
> 
> I do not think that anybody writes UInt64(0) and *wants* the 0 to be built as an Int and then coerced to UInt64.

I can’t think of why anyone would either — all my *LiteralConvertible types just pass on the literal arguments to an init that takes an Int (or whatever) — but “a failure of imagination…”

I guess I’m just saying that with the way Swift treats literals, potential confusion is inevitable, and that it’s better to contain the subtleties to syntax which already involves some implicit behavior, rather than to start rewriting explicit code simply because we think the programmer doesn’t know what they’re doing.

- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160602/5ed1b28e/attachment.html>


More information about the swift-evolution mailing list