将值作为数组的字典一次附加一个,保持为空

问题描述 投票:0回答:1

在ARKit中,我想要做的是收集放置在我的场景中的节点的一堆位置,然后将它们平均,以便节点移动不会像使用ARKit时那样紧张。因此,我将变量声明并初始化为Dictionary,其值为vector_float3的数组。 (我认为这更像是一个比ARKit问题更严重的问题,是吗?)

var extentOfnodesAddedInScene: [SCNNode: [vector_float3]] = [:] 

这与SceneKit / ARKit有关。在不断检测和更新水平平面的渲染器函数中,我想在其中追加vector_float3的数组。

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
    guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
    ...
    extentOfnodesAddedInScene[node]?.append(planeAnchor.center)

但在打印出来时,我得到一个空字典,即[:]

另一个类似的var var nodesAddedInScene: [SCNNode: [vector_float3]] = [:],我在整个数组同时更新时声明并初始化,工作正常。

nodesAddedInScene[node] = [planeAnchor.center, planeAnchor.extent]

因为在最后一个var中只有两个值,所以很好。但对于前者,我希望字典中的数组是动态更新的数组。任何关于如何实现这一目标的指示都会非常有帮助。

arrays swift dictionary arkit
1个回答
1
投票

您可以使用带有默认值的Swift 4 Dictionary Key-subscript来初始化带有空数组的数组,以便即使没有为其键定义任何值也可以附加到该数组。只需确保您的字典值类型是一个数组[SCNNode: [vector_float3]]

extentOfnodesAddedInScene[node, default: []]?.append(planeAnchor.center)
© www.soinside.com 2019 - 2024. All rights reserved.