[swift-evolution] Implicit conversion between primitive types
Matthew Johnson
matthew at anandabits.com
Sat Feb 18 09:55:34 CST 2017
> On Feb 18, 2017, at 7:23 AM, Milos Jakovljevic via swift-evolution <swift-evolution at swift.org> wrote:
>
> Are there are any plans of adding implicit conversion between primitive types?
>
> For example
>
> var float = 5.0
>
> func accept(float: Float) {
> print("this is \(float)")
> }
>
I recently posted a manifesto that covers value subtyping: https://gist.github.com/anandabits/5b7f8e3836387e893e3a1197a4bf144d <https://gist.github.com/anandabits/5b7f8e3836387e893e3a1197a4bf144d>. My opinion is that this is the best way to introduce implicit conversions of the kind you’re talking about here.
That said, without changing how Swift handles type inference for unannotated assignments from literals your example would not work with value subtyping. This is a good thing! It is because the type of `float` is actually `Double` which can represent many values that are not possible to represent with a value of type `Float`.
In order to allow this to work the way you intuitively want we would need `float` to be assigned some kind of `***Literal` type that keeps track of the fact that the value is small enough to be represented by `Float`. This `***Literal` type would be a subtype of `Float`.
> This will raise a warning that double cannot be cast to float. Which is really frustrating since i always have to add type explicitly or cast it to Float.
>
> I would also like to propose to add "f" modifier for floats.
> Any thoughts?
>
> Best,
> Milos Jakovljevic
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170218/2b9e9729/attachment.html>
More information about the swift-evolution
mailing list