How to convert Int to Double in Swift playground?

I created a new playground and wrote the code as follows.

var value = 33 //This will make an integer type of value variable with value 33 value = 22.44 //This doesn't execute as its assigning Double/Float value to an integer. 

I tried

 1. value = Double(value) value = 44.55 //Error here 2. value = Double(33.44) //Error here too. 3. value : Double = 33.22 //Error here too. 

Now what should I do to assign a floating point value to a value.

NOTE. I am participating in a learning level at Swift.

Thanks.

+5
source share
3 answers

Declaring var value = 33 will infer the value type as Int . If you want to assign 33 and make value as Float or Double, you must either declare the type var value : Double = 33 or convert 33 to Double by setting var value = Double(33) .

+12
source

You must set the data type in the variable declaration.

 var value: Double = 33 

But you can also do it like this:

 var value: Double value = 33 

Defining it as var will make the variable mutable, so after defining you can change the value

 value = 33.2 value = 46.1 

If you define a constant or variable that does not need to be changed, you best define it like this:

 let value: Double = 33.2 

If you need this to be Int for any reason at some point, you can pass it to a function or define it like this:

 let intValue = Int(value) 
+1
source

In the first line

 var value = 33 

You created a variable of type Int (because 33 is an integer literal). After that, you cannot assign any other type to it, only Int s. You must create another variable to save the conversion result.

0
source

All Articles