Error casting from Int to Double

Martin Muldoon

I'm trying to understand why casting in the first case works while in the second it fails. What is the difference between the two?

var myVariable = 2

var myDoubleTest1 = Double(myVariable)
var myDoubleTest2 = myVariable as? Double

print(myDoubleTest1)  // 2.0
print(myDoubleTest2)  // nil
Connor Neville
var myDoubleTest1 = Double(myVariable)

This line is just an initializer on Double. It takes an int, and initializes a new double. The documentation is here.

var myDoubleTest2 = myVariable as? Double

The as? keyword in Swift performs a cast. This means, in English, "create a variable named myDoubleTest2. If myVariable is of type Double, then use that. Otherwise, make it nil. We know, from the first line in your code (var myVariable = 2), that myVariable is not a Double (it is an Int), so myDoubleTest2 will be nil. You can read more about type casting here.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Why is the eval class giving me a casting error from int to double?

From Dev

Casting from Java primitive int to double

From Dev

Casting a double result from a divison into an int in Java

From Dev

Eclipse - Java, casting from double to int

From Dev

Casting Double object to int

From Dev

Rounding error when casting from float to int

From Dev

Getting wrong result when casting from double to unsigned int

From Dev

Java Puzzler - casting a double to int

From Dev

Casting double* to int* in C++

From Dev

C++ casting int to double

From Dev

Truncate and casting to int of ceiled double

From Dev

Casting int to double issue in JRockit

From Dev

C++ casting int to double

From Dev

why casting double to int is possible but casting double to String is not possible?

From Dev

Error handling casting to double with stringstream

From Dev

Casting error converting from unsigned int to uint16_t

From Dev

Casting from int64_t to double to int64_t again changes it's value

From Dev

why explicit type casting required from double to float but not from int to byte?

From Dev

Casting don't work (int []to double[])

From Dev

Why is C# casting double to int?

From Dev

Casting of int array into double array in immediate window?

From Dev

Unexpected results on casting betwen int and double

From Dev

Casting of int array into double array in immediate window?

From Dev

Unexpected results on casting betwen int and double

From Dev

Casting Preference for int float vs double

From Dev

Error casting to float, then int in python

From Dev

Error casting to float, then int in python

From Dev

error when casting to int in mvc

From Dev

Stan error casting parameter to int

Related Related

HotTag

Archive