Implicit truncation


(Rudolf Adamkovič) #1

Hi,

I just wanted to ask why there’s no “truncating” label when converting say Float to Int:

let foo: Float = 1.9
let bar = Int(foo)

I do Swift tutoring on the side and the fact that “bar” equals to 1 always surprises my students.

From the Swift API Guidelines:

In “narrowing” type conversions, though, a label that describes the narrowing is recommended.

So, why there’s no “truncating” label in this case?

Thanks!

R+


(Jaden Geller) #2

This is an excellent point. I’d very much support an `Int(truncating:)` and an `Int(rounding:)` initializer from Float.

Cheers,
Jaden Geller

···

On May 21, 2017, at 1:30 PM, Rudolf Adamkovič via swift-evolution <swift-evolution@swift.org> wrote:

Hi,

I just wanted to ask why there’s no “truncating” label when converting say Float to Int:

let foo: Float = 1.9
let bar = Int(foo)

I do Swift tutoring on the side and the fact that “bar” equals to 1 always surprises my students.

From the Swift API Guidelines:

In “narrowing” type conversions, though, a label that describes the narrowing is recommended.

So, why there’s no “truncating” label in this case?

Thanks!

R+

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


(TJ Usiyan) #3

If we had a rounding init for `Int`, I would imagine that we would need an
enum representing the rounding strategies which would get us something like
`Int(rounding:strategy:)` I think that the `.nearest` case would have an
associated value representing the tie breaking strategy as well.

I might be overthinking all of this though.

···

On Sun, May 21, 2017 at 7:29 PM, Jaden Geller via swift-evolution < swift-evolution@swift.org> wrote:

This is an excellent point. I’d very much support an `Int(truncating:)`
and an `Int(rounding:)` initializer from Float.

Cheers,
Jaden Geller

> On May 21, 2017, at 1:30 PM, Rudolf Adamkovič via swift-evolution < > swift-evolution@swift.org> wrote:
>
> Hi,
>
> I just wanted to ask why there’s no “truncating” label when converting
say Float to Int:
>
> let foo: Float = 1.9
> let bar = Int(foo)
>
> I do Swift tutoring on the side and the fact that “bar” equals to 1
always surprises my students.
>
> From the Swift API Guidelines:
>
>> In “narrowing” type conversions, though, a label that describes the
narrowing is recommended.
>
> So, why there’s no “truncating” label in this case?
>
> Thanks!
>
> R+
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution