[swift-evolution] Implicit truncation

Haravikk swift-evolution at haravikk.me
Tue May 23 05:36:39 CDT 2017


This is getting too muddled, so I'm going to summarise thusly; I believe the principle the OP raised is sound, that any initialiser performing a lossy conversion from another type should be clear that this happening, and that a label can do that best, as it makes the conversion self-documenting at the call-site.

Consider for example; with type-inference it's not always obvious what the type of a variable is, and an unlabelled initialiser does nothing to help, like-so:

	var someValue = someMethod()
	…
	var someInt = Int(someValue)

At a glance it's not all obvious what is happening to someValue here; in fact I'd argue that this looks like a lossless conversion, requiring you to find out that someMethod() returns a Float before you can know for sure what's really going on. Whereas the following is more clear:

	var someValue = someMethod()
	…
	var someInt = Int(truncating: someValue)

It may not communicate everything that's happening, but at least now it's clear at a glance that something is happening, and the term truncating suggests that something is being lost/removed from someValue.

Now I don't really care if truncating is the best term for it or not, though I do still think it is and won't change my mind on that; the key thing here is that it's providing that extra safety to developers by making it clear that an important conversion is taking place, and this to me is more consistent with other initialisers on Int etc. where distinctions are made between types that can and cannot be represented exactly.

I'm not saying it should be limited to floats either; I think any initialiser that cannot, or may not, represent the passed value accurately should be labelled for clarity. So passing an Int16 into Int32(_:) would be fine for example, but the reverse should not be.

It's not just an issue of new developers; experienced ones make mistakes too, or forget to consider whether the conversion will impact their code. A label helps, though I still think forcing a decision on rounding is even better, as both prevent a developer from simply throwing in a value in a way that may be a mistake.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170523/6cec8ac8/attachment.html>


More information about the swift-evolution mailing list