4thSpace
4thSpace

Reputation: 44352

Adding Ints and Double always needs conversion?

If I'm going to do something like this:

var total = 0.05 * 6 + 9

Do I need to always do this for it to work?

var total = 0.05 * Double(6) + Double(9)

Upvotes: 0

Views: 61

Answers (2)

JeremyP
JeremyP

Reputation: 86651

To expand on gnasher729's answer, if you find yourself having to (say) add a Double and an Int frequently

e.g.

let six: Int = 6
let nine: Double = 9
var totalError = six + nine // Error!

You can add a function to do it to save typing

func +(lhs: Int, rhs: Double) -> Double
{
    return Double(lhs) + rhs
}

var total = six + nine // OK!

I don't think I'd recommend doing it in the general case though because the whole point of the original restriction is to make you think about the conversion as a source of potential errors. The one case where I think it is totally legitimate is with shift operators

var foo: Int = 5
var bar: UInt64 = 20

var baz = bar << foo // Error!

In the above case, it is totally brain dead that foo needs to be cast to UInt64 IMO, the right hand side of both shift operators should always be an Int.

Upvotes: 1

gnasher729
gnasher729

Reputation: 52566

Numeric literals like 6 or 9 don't have a fixed type, they adapt automatically. So in 0.05 * 6 + 9, 6 and 9 are already of type Double. If you wrote

let six = 6
let nine = 9
var total = 0.05 * six + nine

that wouldn't work, because the 6 on its own has type Int.

Upvotes: 3

Related Questions