Multiplying variables and doubles in swift Multiplying variables and doubles in swift swift swift

Multiplying variables and doubles in swift


You can only multiple two of the same data type.

var billBeforeTax = 100 // Interpreted as an Integervar taxPercentage = 0.12 // Interpreted as a Doublevar tax = billBeforeTax * taxPercentage // Integer * Double = error

If you declare billBeforeTax like so..

var billBeforeTax = 100.0

It will be interpreted as a Double and the multiplication will work. Or you could also do the following.

var billBeforeTax = 100var taxPercentage = 0.12var tax = Double(billBeforeTax) * taxPercentage // Convert billBeforeTax to a double before multiplying.


You just have to cast your int variable to Double as below:

    var billBeforeTax = 100    var taxPercentage = 0.12    var tax = Double(billBeforeTax) * taxPercentage