[swift-evolution] Implicit truncation

Xiaodi Wu xiaodi.wu at gmail.com
Tue May 23 21:34:25 CDT 2017


On Tue, May 23, 2017 at 8:55 PM, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:

> On Tue, May 23, 2017 at 5:27 PM, Guillaume Lessard via swift-evolution <
> swift-evolution at swift.org> wrote:
>
>>
>> > On May 23, 2017, at 13:25, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
>> >
>> > The doc comments in the proposal text were meant as explanation for
>> readers of the proposal; they undergo editing for accuracy during
>> implementation. That wording is, notably, not found in the implemented
>> protocol.
>>
>> What? It shows up in my browser! This is how it looks right now: (in
>> https://github.com/apple/swift/blob/368847b5c7581b9024347f0a
>> 73fc83eb6d9866a8/stdlib/public/core/Integers.swift.gyb#L1366)
>>
>> /// Creates an integer from the given floating-point value, truncating any
>> /// fractional part.
>> ///
>> /// Truncating the fractional part of `source` is equivalent to rounding
>> /// toward zero.
>>
>> Let’s not cherry-pick.
>>
>
> You are quite right; this is still there, and I didn't see it! Well, let's
> fix that.
>
> Is there another lossy initializer for Int or BinaryInteger that doesn’t
>> have a parameter label?
>
>
Yes. First, the Foundation initializer converting from NSNumber has the
same behavior:

```
import Foundation
let x = Int(42.5 as NSNumber) // x == 42
```

More broadly, though, there is a default initializer (i.e., one that does
not use a label for its argument) for conversion from essentially any
standard library numeric type to any other numeric type. Unless every value
of the source type is representable in the destination type (e.g., Int8 to
Int16), all of these initializers can trap at runtime. Now, you might argue
that trapping does not meet your definition of "lossy," but it certainly
causes problems in the example posed above:

```
var someValue = someMethod()
var someInt = Int(someValue)
// Unless you already know the type of `someValue`, there
// is absolutely _no_ guarantee that you'll even reach this
// point, let alone what the value of `someInt` might be.
//
// Trapping is arguably very lossy...
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170523/d671ec07/attachment.html>


More information about the swift-evolution mailing list