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
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.
Comments