[swift-evolution] Implicit truncation

Xiaodi Wu xiaodi.wu at gmail.com
Wed May 24 02:12:01 CDT 2017


On Wed, May 24, 2017 at 01:55 Martin R <martinr448 at gmail.com> wrote:

>
> On 24. May 2017, at 04:34, Xiaodi Wu via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> Yes. First, the Foundation initializer converting from NSNumber has the
> same behavior:
>
> ```
> import Foundation
> let x = Int(42.5 as NSNumber) // x == 42
> ```
>
>
> As of SE-170 (which is implemented in Swift 4), the label "truncating" is
> also used for conversions which loose precision:
>
> let x = Int(42.5 as NSNumber) // // warning: 'init' is deprecated
> let y = Int(truncating: 42.5 as NSNumber) // 42
> let z = Int(exactly: 42.5 as NSNumber) // nil
>

...it is true that SE-0170 gives you a labeled initializer called
`truncating`, but in this case it really does mean truncating the bit
pattern. If the argument is a floating point value, then rounding towards
zero happens before truncating the bit pattern, but this is not why it's
labeled as truncating:

```
import Foundation

let x = Int8(truncating: 442.5 as NSNumber) // -70
let y = Int8(truncating: 442 as NSNumber) // -70
let z = Int8(extendingOrTruncating: 442 as Int) // -70

let a = Int8(442.5) // fatal error
```

This is very important because, if an NSNumber were converted by truncating
the bit pattern if a whole number, but only by rounding if floating point,
then two very close values could be converted very differently. Instead,
this initializer does what it says on the tin: it always truncates the bit
pattern of the value rounded toward zero in order to be representable.
Again, illustrating the importance of consistent usage of this term;
truncating here really does mean truncating the bit pattern.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170524/7ed74b6f/attachment.html>


More information about the swift-evolution mailing list