Swift - Float returns wrong value.

Why Swift is so complicated?

Code Block
let current = 75, total = 100
let calc:Float = Float(current / total)
print(calc)

Expected result: 0.75
Console output: 0.0
Answered by Claude31 in 657562022
Swift is not complicated, but you have to take care of its strong typing.

current and total are Int
hence current / total is inferred as Int, and the Int result or 75/100 is 0

Just write:
Code Block
let calc : Float = Float(current) / Float(total)

Or declare them as Float:
Code Block
let current : Float = 75, total : Float = 100
let calc : Float = current / total
print(calc)

Accepted Answer
Swift is not complicated, but you have to take care of its strong typing.

current and total are Int
hence current / total is inferred as Int, and the Int result or 75/100 is 0

Just write:
Code Block
let calc : Float = Float(current) / Float(total)

Or declare them as Float:
Code Block
let current : Float = 75, total : Float = 100
let calc : Float = current / total
print(calc)

Swift - Float returns wrong value.
 
 
Q