Hacker News new | ask | show | jobs
by Sniffnoy 740 days ago
Wait, in Swift it's illegal to multiply an int by a double?? So you would have to explicitly cast index to a double? I definitely didn't expect that!
7 comments

Implicit conversions in any language are often a source of hard to find bugs. So in general, I find most people agree with the swift design that does not allow such conversions implicitly.
I think this is the correct way to handle this. I don’t know how many times I’ve been stymied by integer arithmetic and precision loss by implicit conversion. How should this be handled? Should the int be converted to a double before the operation, should the double be converted to int before the operation, or should the result be converted to an int or a double? As someone who writes code in many languages in a day, these implicit conversion rules can be difficult to remember. It’s best to enforce the developer to be explicit about the intention.
> Should the int be converted to a double before the operation, should the double be converted to int before the operation, or should the result be converted to an int or a double?

Isn't it pretty evident that implicit conversions should only go from integer to floating point?

> precision loss by implicit conversion

That's a reasonable worry, but "Int" in general is only safe to store 32 bits, and 32 bit integers will losslessly convert to doubles.

The alternative is to do what JS does: https://www.destroyallsoftware.com/talks/wat
It strikes a balance, by allowing _literals_ to be implicitly converted as needed.

E.g. `someDouble * 1` is valid, without needing to write `1.0` or `1f`.

This is because `Double` conforms to the `ExpressibleByIntegerLiteral` protocol. There's other similar protocols for other literal types, which e.g. you could write:

    let s: Set = [1, 2, 3]
Where it would have defaulted to being an Array without the annotation.
No cast, just a conversion, depending on how you want the math to work. int * double would usually be Double(int) * double.
One could overload the * infix operator to support this type of multiplication. It just doesn’t come with the standard library.
You could overload * if you really don't want to convert the int manually