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
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
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.
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.
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) }