[swift-evolution] Proposal: Auto-convert for numbers when safe

Douglas Gregor dgregor at apple.com
Sat Dec 12 14:43:14 CST 2015


> On Dec 12, 2015, at 12:03 AM, Manav Gabhawala <manav1907 at gmail.com> wrote:
> 
> Thanks for your feedback Doug.
> 
> With regards to your first concern, I think that we won't actually lose any symmetry because if the user actually wants backward conversions they will define it themselves

Right now, our subtype-to-supertype conversions are reversible. I think it would be unfortunate to lose that property, and I don’t believe it’s feasible to maintain that property in a language with user-defined conversions without an unacceptable runtime performance penalty.

> and so we won't ever have the case where we are giving this behavior for "free" and so the compiler will only have to do a one level check of an implicit conversion. And while we want to support the castingFrom implicit initializer (which can be failable if need be) it will always be user defined and never generated by a protocol extension or the compiler so things will still be Swifty. 

I realize that my second example didn’t demonstrate the issue properly, so I’ll try again. Here’s the example:


	struct X {
	  implicit init(_ y: Y) { … }
	}

	struct Y {
	  init?(castingFrom: X) { … }
	}

	var x: X = Y()
	var any: Any = x
	let y = any as? X { } // this is the interesting bit

Having reversible conversions implies that this as? cast should succeed, but how would that happen? The Swift runtime would need to query the dynamic type of “any” (it’s an X), then follow the runtime-generated DAG of conversions (backwards), calling init?(castingFrom:) at the appropriate points to attempt the cast. That’s complicated and bound to be slow.

> From a technical standpoint I can't say much because I have no compiler experience whatsoever (yet). But I can see how this might mess around with the type checker and I can understand why this might be too difficult to implement for swift 3. However, I strongly believe the current numbers model of explicit conversion is too verbose and very non swift like. One of the biggest problems is the way that Int types are imported from C libraries and you have to keep converting back and forth between for example a UInt32 and an Int or something similar. Would you be open to restricting the feature to only work with number types and "hard code" that behavior into the compiler for swift 3 or do you think that's something we should not proceed with, or have a different solution for solving the numbers problem?

I understand the problem you’re trying to solve, and I don’t have a good solution to it. However, generalized user-defined conversions is, for me, too big a hammer for solving this particular problem.

	- Doug




More information about the swift-evolution mailing list