将值作为数组的字典在每次追加一个时保留为空 [英] Dictionary with values as array on appending one at a time, remains empty

查看:77
本文介绍了将值作为数组的字典在每次追加一个时保留为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]] = [:] 

这与SceneKit/ARKit有关.在不断检测和更新水平面的渲染器函数中,我想在其中附加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., [:]

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

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]

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

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.

推荐答案

您可以使用具有默认值的基于Swift 4字典键的下标初始化带有空数组的数组,以便即使没有数组也可以追加到该数组尚未定义其键的值.只要确保您的字典值类型是数组[SCNNode: [vector_float3]]:

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)

这篇关于将值作为数组的字典在每次追加一个时保留为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆