binary operator / cannot be applied to operands of type Int and Double

9.6k views Asked by At

Hello brand new to Swift, and programming in general. Going through an exercise the code given is exactly:

//: Playground - noun: a place where people can play

import UIKit

let height = 12
let width = 10


let area = height * width

let areaInMeters = area / 10.762

But I get the error, "binary operator / cannot be applied to operands of type Int and Double".

After some digging around I found you can't operate on both an Integer and a Double. So I changed the last line to:

let areaInMeters = (Double)area / 10.762

Then I get the error, "Consecutive statements on a line must be separated by a ;" and it wants me to put the ; after area. None of this is making any sense to me.

Using El Capitan beta and Xcode 7 beta.

2

There are 2 answers

0
LArmer On

Try instead adding a decimal point and a zero to the end of your height and width.

Like so:

let height = 12.0 let width = 10.0

And you won't have to worry about having to deal with an Integer. Hope this helps. Happy Coding!

0
Paul Ardeleanu On

height and width will both be inferred as of type Int. Therefore area is also of type Int whilst 10.762 is a Double.

And in Swift safety is paramount so you'll need to have both operands of same type.

Solution is (as Eric D. suggested) is to convert area to a Double:

let areaInMeters = Double(area) / 10.762