[swift-evolution] Proposal: 'T(literal)' should construct T using the appropriate literal protocol if possible
Ben Rimmington
me at benrimmington.com
Fri Jun 3 22:11:47 CDT 2016
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>
-- 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