+ 1
How does this typecasting work?
Consider this code in Swift: print(23 / 10) var a: Float = 23 / 10 print(a) 23 / 10 evaluates to 2. But then what happens in the 2nd line? I had thought that the integer result '2' will be converted to a Float. It seems not. Why?
5 Answers
+ 3
Looks like output is the same what you thought đ€
https://code.sololearn.com/cl88WFfq2zUd/?ref=app
+ 3
Because, Swift is a type safe language, meaning that it supports clarity when specifying value types for code. When part of your code expects a float, you can't pass it an int by mistake.
https://en.m.wikipedia.org/wiki/Type_safety
+ 2
NotAPythonNinja Or is it that the compiler type-casts 23 to 23.0? Thank you.
+ 2
Simba So I assume that '23 / 10' is converted to '23.0 / 10'?. This is contradictory to what C does. I wonder how the compiler does this.
P.S. Conclusion: The compiler converts every integer into a Float.
0
Simba (23 / 10) evaluates to '2'. Then how does the second print statement print 2.3?