我对 Swift 比较陌生,尚未掌握可选的安全方面。
我有一个类型为[String: [SCNNode]]
的字典。给定分子将具有多个组件作为 [SCNNode]
中的元素。对于该分子,我检索该组件数组并将每个元素分配给本地 SCNNode
进行显示、操作和动画。
let components = moleculeDictionary["aceticAcid"] // the array of components
// [baseMolecule, hydrogenCharge, oxygenCharge, ionizingH, ionizedBond, bonds]
atomsNode_1 = components![0] // baseMolecule
baseNode.addChildNode(atomsNode_1)
atomsNode_5 = components![3] // ionizingH
atomsNode_1.addChildNode(atomsNode_5)
// etc.
在尝试选择性地绑定(bind)它时,编译器似乎对此感到满意。
if let node = components?[0] { // baseMolecule
baseNode.addChildNode(node)
}
我不清楚?。我对此的阅读表明我们正在以一种不关心是否有零的方式展开。但这是否使这个可选绑定(bind)比上面的强制展开更好?或者这是“可选链”?我是否应该在分配组件
时进行检查?我应该担心这里的安全吗?我所做的唯一“upsteam”测试是在将字典存档分配给 moleculeDictionary
之前检查它是否存在。
我将有数百个这样的作业,所以我想把它做好。欢迎就处理此问题的最佳方法提出建议!
谢谢,伯恩
最佳答案
在我看来,你应该担心 Swift 的安全性。鉴于上面的代码,我将在第一遍中将其重写为:
guard let components = moleculeDictionary["aceticAcid"] where components.count > 3 else { // handle the case where there is no value for this key, or not enough nodes }
// Now I know that I have the correct number of components I don't need to force unwrap:
atomsNode_1 = components[0] // baseMolecule
baseNode.addChildNode(atomsNode_1)
atomsNode_5 = components[3] // ionizingH
atomsNode_1.addChildNode(atomsNode_5)
这是第一个第一遍。第二遍是确保我拥有所有组件的值,即编写一个结构体来包含 SCNNode 值,以便每个节点要么有一个值,要么有一个 nil,您可以然后相应地构建您的节点结构。
编辑添加
这是第二遍的指示 - 它确实需要比我更多的领域知识,但这是一个开始。
看来你是从[[SCNNode]]
(一个由SCNNode
组成的数组组成的数组,其中每个子数组的位置都很重要。这到它自己的结构中,这样:
struct Molecule {
let baseMolecule: [SCNNode]?
let hydrogenCharge: [SCNNode]?
let oxygenCharge: [SCNNode]?
let ionizingH: [SCNNode]?
let ionizedBond: [SCNNode]?
let bonds: [SCNNode]?
// Other methods can be written to build up atom nodes from within the struct which handle the cases where the component array is nil
}
关于swift:安全访问 SCNNode 数组的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35657868/