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

Brent Royal-Gordon brent at architechies.com
Thu Jun 2 16:43:08 CDT 2016


> In my opinion, using this initializer-call syntax to build an explicitly-typed literal is an obvious and natural choice with several advantages over the "as" syntax.  However, even if you disagree, it's clear that programmers are going to continue to independently try to use it, so it's really unfortunate for it to be subtly wrong.

I've seen developers do this; in one memorable case, it resulted in Swift taking a ridiculously long time to typecheck an expression, since the seemingly pinned-down types of the literals had actually become *more* ambiguous, not less.

However, it's not difficult to teach developers to use `as`. Usually what's happening is that their mental model of the language is wrong: they think of `UInt16(foo)` as a cast to a primitive type, and are surprised to learn that it's actually an initializer on a struct and they're initializing an instance. Learning this helps them understand how the language works, what the difference is between initializers and `as`, and how they can write the same things they see in the standard library types.

I think *actually* turning this into magic would be counterproductive. The better solution is to make the compiler replace me in that story, by having it emit a warning with a fix-it. It keeps initializer calls meaning exactly what they say. (And it doesn't require an evolution proposal to do, since you can add a warning with a mere bug.)

	UInt16(42)
	^~~~~~ ^~
	Use of initializer with integer literal does not cast '42' to 'UInt16'
	Fix-It: Replace with '42 as UInt16'

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list