问题
In ARKit, what I am trying to do is gather a bunch of positions of node placed in my scene and then average those out so that the node movements are not jittery as what happens while using ARKit. Hence, I have a variable declared and initialised as a Dictionary with values as an Array of vector_float3. (I am thinking this is more of a Swift problem than ARKit problem, is it?)
var extentOfnodesAddedInScene: [SCNNode: [vector_float3]] = [:]
This is related to SceneKit/ ARKit. Within the renderer function which keeps detecting and updating horizontal planes, I want to append the array of vector_float3 within.
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
...
extentOfnodesAddedInScene[node]?.append(planeAnchor.center)
But on printing this out, I am getting an empty dictionary, i.e., [:]
Another similar kind of var var nodesAddedInScene: [SCNNode: [vector_float3]] = [:]
which I have declared and initialized when I am updating at the same time with the whole array, is working fine.
nodesAddedInScene[node] = [planeAnchor.center, planeAnchor.extent]
Since, in the last var there will only be two values, it is fine. But for the former one, I want the array within the dictionary to be a dynamically updated one. Any pointers towards how to achieve this end would be very helpful.
回答1:
You can use Swift 4 Dictionary Key-based subscript with default value to initialize your array with an empty array to be able to append to it even when there is no value yet defined to its key. Just make sure your dictionary value type is an array [SCNNode: [vector_float3]]
:
extentOfnodesAddedInScene[node, default: []]?.append(planeAnchor.center)
来源:https://stackoverflow.com/questions/47929937/dictionary-with-values-as-array-on-appending-one-at-a-time-remains-empty