Chapter 2, About Type conversion, what happening?

var integer: Int = 100
var decimal: Double = 12.5
integer = Int(decimal)
I just wonder to know that which method to call!
how it happened internal call to change type conversion?
//integer = Int(exactly: <#T##Double#>)
//integer = Int(<#T##source: Double##Double#>)
//integer = struct Int : FixedWidthInteger, SignedInteger

Hi @tom16,
what is it that you want to exactly do? When you are trying to instantiate an Int from a Double as in your example of 12.5, what do you want it to be? 12 or 13?

If you instantiate it as an Int, it will give you the value of 12, however if your round it, it will give you the value of 13 which will still remain a Double.

let decimal = 12.5
let int1 = Int(decimal)
let int2 = Int(decimal.rounded())
print(int1, int2) // 12  13

cheers,

Jayant

thank you very much, I also wonder to know in Int struct , which method to call in default ?

Hi @tom16,
You should use the Int(number) function, while you can see the other options, they are not really something that you can choose. They are convenience initialisers for different type of data types. You can intitialize an Int from a CGFloat, Float, Float80, Double, NSNumber.

So in my opinion, to keep things simple, simply initialise or convert a floating point/decimal number to an Int simply by using Int(number)

You can know more about the int structure form the Apple Documenation page on Int which is found at Apple Developer Documentation

cheers,

Jayant

This topic was automatically closed after 166 days. New replies are no longer allowed.