-2

I am comming from C# and started checking swift for iOS and got the following issue...

I just want to convert pence amount to pounds and finding problem with integer division in swift. Following is the error I am getting.

enter image description here

What I can't understand is, it works ok in line 38 way but the same erroring in line 40 when using variable.

Edits

decVal1 = 23.4 which is correct. Why decVal2 can't have the same?

JibW
  • 4,538
  • 17
  • 66
  • 101

3 Answers3

5

What I can't understand is, it works ok in line 38 way but the same erroring in line 40.

On line 38, the compiler is inferring the type of the values to be something that satisfies the requirement that decVal1 should be a Double.

On line 40, you're explicitly telling the compiler that myNumber is an int, thus removing the compiler's ability to decide that it's something else.

Caleb
  • 124,013
  • 19
  • 183
  • 272
4

In Swift you cannot do math with different types (in this case Int and Double). Even Int and UInt are not interchangeable.

You have to create new instances of the matching type

var myNumber : Int = 2340
var doubleDiv : Double = Double(myNumber) / 100.0

the decimal places in literals are not necessary in most cases, but it is clearer to use the same signatures.

vadian
  • 274,689
  • 30
  • 353
  • 361
2

You have to convert Int to Double

var testInt : Int = 4
var testDouble : Double = 333 / 222
var testDouble2 : Double = Double(testInt) / 222

at the testDouble compiler directly takes the 333 and 222 to double but you have tried to divide Int. The type should be same for both.

With your code :

var testInt : Int = 2340
var testDouble : Double = 2340 / 100
println(testDouble)
var testDouble2 : Double = Double(testInt) / 100
println(testDouble2)

Output :

23.4

23.4

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136