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

John McCall rjmccall at apple.com
Sat Jun 4 00:29:09 CDT 2016


> On Jun 3, 2016, at 8:11 PM, Ben Rimmington <me at benrimmington.com> wrote:
> I think your original proposal is good, but just in case:
> 
> [Currently]
> 
>    // Literal `7` is converted to `Swift.IntegerLiteralType` typealias.
>    UInt16(7) calls UInt16.init(_ value: Int)
> 
> [Suggested]
> 
>    // Literal `7` is converted to `UInt16.IntegerLiteralType` associatedtype.
>    UInt16(7) calls UInt16.init(_ value: UInt16)
> 
> Have "user-defined literals" already been rejected for Swift?
> <https://en.wikipedia.org/wiki/C%2B%2B11#User-defined_literals>
> <https://en.wikipedia.org/wiki/C%2B%2B14#Standard_user-defined_literals>

I don't know that we've ruled out using literal suffixes, but it's not really relevant.
We already have a syntax for coercing a literal to a specific type; the problem is
that people are writing UInt8(7) anyway, and it's completely reasonable for them
to expect that to work.  So even if we added user-defined literal suffixes as a
feature, we'd still have this problem.

I can imagine Swift adding literal suffixes, but only to enable a units library, not
to provide yet another way to specify type widths.

John.


> 
> -- Ben
> 
>> On 4 Jun 2016, at 02:20, John McCall <rjmccall at apple.com> wrote:
>> 
>>> On Jun 3, 2016, at 5:31 PM, Ben Rimmington via swift-evolution <swift-evolution at swift.org> wrote:
>>> John McCall wrote:
>>> 
>>>> I think that's a very promising way of thinking about literals.  Writing
>>>> a literal creates a notional value whose type is the informal, infinite-
>>>> precise type of all integer/FP/collection/etc. literals, which (1) can be
>>>> implicitly converted to any type that implements the appropriate protocol
>>>> and (2) in fact *must* be converted to some such type (possibly the
>>>> default type for that literal) in order for the code to be executable.
>>> 
>>> Could you allow IntegerLiteralConvertible.IntegerLiteralType associatedtype
>>> to override the default Swift.IntegerLiteralType typealias iff there's more
>>> than one unlabelled init(_:) to choose from? Then you can call the "correct"
>>> init(_:) instead of calling init(integerLiteral:) as a "special case".
>> 
>> This is essentially already how it works.  The literal protocols are not invoked via
>> overload resolution; Swift always invokes the initializer that satisfies the protocol
>> requirement.
>> 
>> That is, you can provide ten different init(integerLiteral: T) initializers, but that will
>> just prevent the compiler from inferring the associated type, so you'll have to
>> declare it.  Once you do, that associated type will determine the initializer that
>> satisfies the requirement, and that'll always be the initializer chosen.
>> 
>> John.
> 



More information about the swift-evolution mailing list