3 ms·
Both of your questions have the same answer: Swift doesn't implicitly convert between types. First answer: since Swift has no implicit conversions, greedily se
by gilgoomesh 10y ago
Both of your questions have the same answer: Swift doesn't implicitly convert between types.
First answer: since Swift has no implicit conversions, greedily selecting types would create a situation where mathematical expressions or even function parameters that use Float instead of Double would be completely impractical. Every floating point literal would be interpreted as Double and compiler error on attempt to use as a Float. You'd need to manually construct a Float around every literal to actually get Float. The same problem would plague and UInt, Int8, etc – any value would require manual construction from a literal of type Int.
Second answer: Since Swift has no implicit conversions:
let a: Double = -(Int.max) + -(Int.max)
would always be a compile error because the right-hand side is an Int and can't be converted to Double. This isn't a type inference or type checking problem, it's a "no implicit conversions allowed" error. You would need to write:
let a = Double(-(Int.max) &+ -(Int.max))
for the line to compile (I've used the overflow allowed addition operator '&+' since the regular '+' will trigger an abort if it actually overflows).
- espadrine 10y agoThe idea of having a select number of explicitly defined implicit conversions is interesting, though, but not unheard of. (Is there not something like that in Scala?) However, in order to perform the simplistic algorithm that the parent comment imagines, we have to give up overloading. If you have f(A) and f(B) and an implicit conversion between A and B, and we type f(x) (where x is an A), both f(A) and f(B) could be selected. Since they might have different types, a larger expression it is a part of could be valid by picking one and not the other, but we cannot know which until we go through all possibilities. That's an exponential algorithm too.
- paulddraper 10y agoYes, Scala has that. There's a precedence, and ties are compile errors.It It won't apply more then one level of conversion, though you can perform recursive operations in the type system. Shapeless is a library that uses this for ad-hoc typesafe programming without boilerplate.
- im4w1l 10y agoOk, so what if you type out int max manually? let a: Double = -(9223372036854775807) + - (9223372036854775807)
- gilgoomesh 10y agoIn that case, all literals would be interpreted as Double.