swift – binary operator * cannot be applied to operands of type Int and Double

swift – binary operator * cannot be applied to operands of type Int and Double

You should convert one type to the other one so both variable should be the same types:

n

var result: Double = Double(textfield) * VATn

Its because youre trying to multiply an Int (textfield) with a Double (VAT). Because with such an operation you could lose the precision of the double Swift doesnt allow to convert one to the other so you need to explicitly cast the Int to a Double …

n

var result = Double(textfield) * VATn

swift – binary operator * cannot be applied to operands of type Int and Double

The problem here is that the statement given is literally true, because Swift is strongly typed and doesnt coerce implicitly. Just had a similar case myself with binary operator – cannot be applied to operands of type Date and Int.

n

If you write:

n

var result = 10 * 0.2n

n

…thats fine, but if you write:

n

var number = 10nvar result = number * 0.2n

n

…thats not fine. This is because untyped explicit values have an appropriate type selected by the compiler, so in fact the first line is taken as being var result = Double(10) * Double(0.2). After all, as a human being you might mean 10 to be floating-point or an integer – you normally wouldnt say which and would expect that to be clear from context. It might be a bit of a pain, but the idea of strong types is that after the code is parsed it can only have one valid compiled expression.

n

In general you would build a new value using the constructor, so var result = Double(textfield) * VAT in your case. This is different from casting (textfield as Double) because Int is not a subclass of Double; what you are doing instead is asking for a completely new Double value to be built at runtime, losing some accuracy if the value is very high or low. This is what loosely typed languages do implicitly with pretty much all immediate values, at a small but significant time cost.

n

In your specific case, it wasnt valuable to have an Int in the first place (even if no fraction part is possible) so what you needed was:

n

func taxesFree(number: Int) -> Double {n    var textfield = Double(self.inputTextField.text)!n    let VAT = 0.2n    var result = textfield * VATn    return resultn}n

Leave a Reply

Your email address will not be published.