一次添加一个值作为数组的字典,保持为空 [英] Dictionary with values as array on appending one at a time, remains empty

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

问题描述

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

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 Dictionary Key-based 下标来初始化您的数组,使用一个空数组,即使没有value 尚未定义为其键.只要确保你的字典值类型是一个数组 [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天全站免登陆