Casting Optional

I have the following line in my code.

if var rootPosition = entity?.component(ofType: RootNodeComponent. self)?.rootNode.position {

Position (right hand side) is an "SCNVector3?". I want rootPosition to be in my own vector class, Vector. How can I do this cast? Providing an init for my Vector class which takes an SCNVector3 isn't enough. I have tried a few simple things such as the following, but no luck so far.

if var rootPosition: Vector = entity?.component(ofType: RootNodeComponent. self)?.rootNode.position {

Which gives me the following error.

Cannot convert value of type 'SCNVector3?' to specified type 'Vector?'

Thanks!

Optional.map will work, or you could just unwrap first and convert after.

1 Like

Cool map works. I wonder if I'm doing too much in one line, might convert later.

if var rootPosition = (entity?.component(ofType: RootNodeComponent. self )?.rootNode.position).map({ Vector(scnVector3: $0) }) {