Swift 上的 if var 闭包的范围



我正在使用 Swift 实现邻接列表。

现在我想添加 Edge,如果字典中已经存在该值,我想附加一个新的边缘。

但是,if var 的范围似乎只在以下闭包内,这意味着

if var child = children[from] {
// child exists
child.append(to)
}

不会产生预期的结果,但以下内容会产生

if var child = children[from] {
children[from]!.append(to)
}

但这看起来很丑陋,坦率地说是错误的。

在这种情况下,附加到字典的最佳方法是什么?

由于字典值是[Int]的值类型,因此将创建字典值的副本并提供给child。这意味着您对 child 所做的任何更改都不会反映在字典中。因此,您需要将该值替换为已进行更改的值。

if var child = children[from] {
child.append(to)
children[from] = child
}

或者简单地说,

children[from]?.append(to)