Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a simple division of Double by Int in Swift?

Tags:

swift

Looking at various posts on this topic but still no luck. Is there a simple way to make division/conversion when dividing Double (or Float) with Int? Here is a simple example in playground returning and error "Double is not convertible to UInt8".

    var score:Double = 3.00
var length:Int = 2  // it is taken from some an array lenght and does not return decimal or float

var result:Double = (score / length )
like image 851
Artis Universe Avatar asked Mar 19 '15 08:03

Artis Universe


People also ask

Can you add int and double 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.

How do you split two variables in Swift?

To divide a value by another in Swift, use the division operator (/).


2 Answers

Cast the int to double with var result:Double=(score/Double(length)) What this will do is before computing the division it will create a new Double variable with int inside parentheses hence constructor like syntax.

like image 82
riodoro1 Avatar answered Sep 28 '22 13:09

riodoro1


You cannot combine or use different variable types together. You need to convert them all to the same type, to be able to divide them together. The easiest way I see to make that happen, would be to make the Int a Double. You can do that quite simply do that by adding a ".0" on the end of the Integer you want to convert.

Also, FYI: Floats are pretty rarely used, so unless you're using them for something specific, its also just more fluid to use more common variables.


like image 26
Ronn Weasley Avatar answered Sep 28 '22 14:09

Ronn Weasley