0

Am I missing something or typecast is obligatory while adding numbers having different types:

var i:Int=5
var d:Double=6.0

var q:Double= i + d // this is error?!
var w:Double= Double(i) + d // this is ok
AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210

3 Answers3

1

Am I missing something or typecast is obligatory while adding numbers having different types:

No you are not missing something, typecasting is obligatory.

I think it's fine for arithmetic operations because it makes you think about your type conversions, however, the same rule applies to bit shifting. i.e.

var i: UInt64 = 6
var j: Int = 3
var k = i << j // error

This is really annoying and wrong. I've raised a bug with Apple, but they haven't done anything about it yet.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
1

Swift doesn't provide automatic conversion between numeric types.

Normally you just perform conversions like you used in your question.

I don't recommend it, but you could do this:

func +(i:Int, d:Double) -> Double {
    return Double(i) + d
}

let i: Int = 1
let d: Double = 7.0
i + d
// result: 8.0

You would need to provide a lot of overrides to cover all the bases. Like I said, I don't recommend it.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • 1
    Note `1 + 7.0` would work anyway. "The rules for combining numeric constants and variables are different from the rules for numeric literals. The literal value 3 can be added directly to the literal value 0.14159, because number literals do not have an explicit type in and of themselves. Their type is inferred only at the point that they are evaluated by the compiler." – Mike Pollard Oct 09 '14 at 15:59
-1

I know it's unsafe but for some big math routines it's ok, using @Mike Pollard method to override default + & - operators :

func + (left: Int, right: Double) -> Double { return Double(left) + right }
func + (left: Double, right: Int) -> Double { return left + Double(right) }
func - (left: Int, right: Double) -> Double { return Double(left) - right }
func - (left: Double, right: Int) -> Double { return left - Double(right) }
JeremyP
  • 84,577
  • 15
  • 123
  • 161
AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210