4 ms·
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!
by Sniffnoy 2y 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!
- manmal 2y agoOne could overload the * infix operator to support this type of multiplication. It just doesn’t come with the standard library.
- jshier 2y agoNo cast, just a conversion, depending on how you want the math to work. int * double would usually be Double(int) * double.
- wlesieutre 2y agoYou could overload * if you really don't want to convert the int manually
- redwoolf 2y agoI 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.
- Dylan16807 2y ago> 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.
- jb1991 2y agoImplicit 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.
- jayyhu 2y agoThe alternative is to do what JS does: https://www.destroyallsoftware.com/talks/wat https://www.destroyallsoftware.com/talks/wat
- amomchilov 2y agoIt 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.