[swift-evolution] Implicit truncation

Haravikk swift-evolution at haravikk.me
Mon May 22 09:30:55 CDT 2017

> On 22 May 2017, at 15:09, Xiaodi Wu via swift-evolution <swift-evolution at swift.org> wrote:
> Let's be clear: it _is_ rounded, just toward zero. It is consistent with the behavior of integer division. I would guess that your students also repeatedly struggle with the result that `2 / 3 == 0`? If so, they have not been taught some important fundamentals of integer arithmetic. If not, then it should be natural that `Int(2 / 3 as Double == Int(2 / 3 as UInt)`.

Just to add my thoughts; but while I agree that it's important developers learn the intricacies of Int vs. Float, I don't think this is quite the same issue as divisions.

If you're asking for an Int then you should have some idea that you're asking for a whole number only, and so that follows on to division as Ints simply cannot handle fractions.

However, for conversion from Float there's an expectation that some rounding must occur, the problem is that it's not as expected; while you or I would expect it to be this way with familiarity of other languages, for someone new to the language this isn't always going to be the case. While it's reasonable to expect new developers to know what an Int is, I think it's unreasonable for them also to remember what the default rounding strategy of an implicitly rounding constructor is.

For this reason I tend to agree with the principle that the Int(_:Float) constructor should probably be labelled more intuitively, personally I'd like to see:

	func init(truncating:Float) { … }
	func init(rounding:Float, _ strategy: FloatingPointRoundingRule) { … }

Here the init(truncating:) constructor is just a convenience form of init(rounding:) with a strategy of .towardZero, which I believe is consistent with the current behaviour. It's also easily swapped in anywhere that init(_:Float) etc. are currently used.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170522/0ee871de/attachment.html>

More information about the swift-evolution mailing list