Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 889
Phil Hanson Avatar asked Jun 16 '15 13:06

Phil Hanson


2 Answers

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
like image 152
Paul Ardeleanu Avatar answered Nov 11 '22 16:11

Paul Ardeleanu


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!

like image 40
LArmer Avatar answered Nov 11 '22 16:11

LArmer