Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying variables and doubles in swift

I'm a designer looking into learning Swift and I'm a beginner.

I have no experience whatsoever.

I'm trying to create a tip calculator using basic code in Xcode's playground.

Here is what I have so far.

var billBeforeTax = 100
var taxPercentage = 0.12
var tax = billBeforeTax * taxPercentage

I get the error:

Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'

Does this mean I can't multiply doubles?

Am I missing any of the basic concepts of variables and doubles here?

like image 618
btothemoon Avatar asked Jun 05 '15 22:06

btothemoon


People also ask

How do you multiply variables in Swift?

To perform multiplication of two numbers in Swift, we can use Swift Multiplication Arithmetic operator. Multiplication Operator * takes two numbers as operands and returns the product of the two operands. a and b can be Int. a and b can be Float.

Can you multiply int and double?

This is not possible.

Can you add double and INT in Swift?

As a result of all this, Swift will refuse to automatically convert between its various numeric types – you can't add an Int and a Double , you can't multiply a Float and an Int , and so on.


2 Answers

You can only multiple two of the same data type.

var billBeforeTax = 100 // Interpreted as an Integer
var taxPercentage = 0.12 // Interpreted as a Double
var 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 = 100
var taxPercentage = 0.12
var tax = Double(billBeforeTax) * taxPercentage // Convert billBeforeTax to a double before multiplying.
like image 154
omoman Avatar answered Nov 16 '22 00:11

omoman


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

    var billBeforeTax = 100
    var taxPercentage = 0.12
    var tax = Double(billBeforeTax) * taxPercentage
like image 44
Icaro Avatar answered Nov 16 '22 00:11

Icaro