Search code examples
iosswiftswift-playground

Multiplication of Integer by double and storing result as a double


Out of plain curiosity, in swift:

var a:Double = 3.5
var b:Int = 4
var c = a * Double(b)
var d:Double = a * b

Why is d not valid but c is? Since I'm specifying that d is a double, shouldn't the compiler detect that b should be casted to a double?


Solution

  • In Swift, you must explicitly convert types, instead of cast it. See the document.

    Because each numeric type can store a different range of values, you must opt in to numeric type conversion on a case-by-case basis. This opt-in approach prevents hidden conversion errors and helps make type conversion intentions explicit in your code.

    When you have b:Int, you can Double(b), because it's conversion from Int to Double, but you cannot b as Double or c: Double = b because it's casting.

    As for var d:Double = a * b, The problem is that there is no * operator implementation which accepts Double and Int as operands and returns Double.

    If you want, you can implement overloaded operator:

    func *(lhs:Double, rhs:Int) -> Double {
        return lhs * Double(rhs)
    }
    
    var d:Double = a * b // -> 14
    

    But I don't recommend to do that. You should do explicit conversion instead.