brw59 brw59 - 1 month ago 7x
Swift Question

swift fatal error: unexpectedly found nil while unwrapping an Optional value with Any Array

I realize there have been several 'similar' errors posted about this, but they don't seem to be helping me in my case. It's also possible the syntax isn't working how I'm expecting it to work in Swift:

There are no compile errors, or warnings, just a runtime error

var allPlayerSpawnState: Array<Array<Any>>!

var pName: String = "defaultPlayerName"
var pShape = "box"
var pDimensions = SCNVector4(1,1,1,0)
var pPosition = SCNVector3(0, 0, 0)
var pRotation = SCNVector3(0, 0, 0)
var pForce = SCNVector3(0, 0, 0)
var pTorque = SCNVector4(0, 0, 0, 0)
var pSkinArray = [UIColor]()
var pEmitter = false
var pEmitterUIColor = UIColor.random() // custom random color
var pState: SCNPhysicsBodyType = .Static

... values change here


let tempArray: Array<Any> = [pName, pShape, pDimensions, pPosition, pRotation, pForce, pTorque, pSkinArray, pEmitter, pEmitterUIColor, pState]
allPlayerSpawnState.append(tempArray) // runtime error here: "Thread 1: EXE_BAD_INSTRUCTION (code=EXE_I386_INVOP, subcode=0x0)"

... later wanting to use it like this:

for i in allPlayerSpawnState {
some_function(i[0] as! String, pShape: i[1] as! String, pDimensions: i[2] as! SCNVector4, pPosition: i[3] as! SCNVector3, pRotation: i[4] as! SCNVector3, pForce: i[5] as! SCNVector3, pTorque: i[6] as! SCNVector4, pSkinArray: i[7] as! [UIColor], pEmitter: i[8] as! Bool, pEmitterUIColor: i[9] as! UIColor, pState: i[10] as! SCNPhysicsBodyType)

and here is the output

SCNVector4(x: 1.0, y: 1.0, z: 1.0, w: 0.0)
SCNVector3(x: 0.0, y: -10.0, z: 0.0)
SCNVector3(x: 0.0, y: 0.0, z: 0.0)
SCNVector3(x: 0.0, y: 0.0, z: 0.0)
SCNVector4(x: 0.0, y: 0.0, z: 0.0, w: 0.0)
[UIDeviceRGBColorSpace 1 0 1 1]
UIDeviceRGBColorSpace 0 1 0 1

fatal error: unexpectedly found nil while unwrapping an Optional value

when I option-click the elements in the array, none of them are optional, so I don't know what the error is trying to indicate.

Any help is appreciated. If you know of a way I can do it without using "Any" that might help me prevent a future potential problem indicated after "... later wanting to do it like this:"


The array is declared but not initialized. At the moment you are going to append something to the array it's nil and causes a runtime error.

Initialize the array this way:

var allPlayerSpawnState = Array<Array<Any>>()