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 )
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.
To divide a value by another in Swift, use the division operator (/).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With