How does this typecasting work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

23rd Jul 2021, 10:57 AM
Calvin Thomas
Calvin Thomas - avatar
5 Answers
+ 3
Looks like output is the same what you thought 🤔 https://code.sololearn.com/cl88WFfq2zUd/?ref=app
23rd Jul 2021, 11:31 AM
Simba
Simba - avatar
+ 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
23rd Jul 2021, 12:08 PM
Simba
Simba - avatar
+ 2
NotAPythonNinja Or is it that the compiler type-casts 23 to 23.0? Thank you.
23rd Jul 2021, 12:08 PM
Calvin Thomas
Calvin Thomas - avatar
+ 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.
23rd Jul 2021, 2:31 PM
Calvin Thomas
Calvin Thomas - avatar
0
Simba (23 / 10) evaluates to '2'. Then how does the second print statement print 2.3?
23rd Jul 2021, 11:37 AM
Calvin Thomas
Calvin Thomas - avatar