首页 > 解决方案 > Swift 上 if var 闭包的范围

问题描述

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

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

但是, if var 的范围似乎只在以下闭包之内,意思是

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

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

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

但这看起来很难看,而且坦率地说是错误的。

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

标签: swift

解决方案


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

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

或者简单地说,

children[from]?.append(to)

推荐阅读