swift - 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)
}
但这看起来很难看,而且坦率地说是错误的。
在这种情况下,附加到字典的最佳方法是什么?
解决方案
由于您的字典值是一个值类型 [Int]
,因此会制作字典值的副本并将其提供给child
。这意味着您对孩子所做的任何更改都不会反映在字典中。因此,您需要将值替换为您进行更改的值。
if var child = children[from] {
child.append(to)
children[from] = child
}
或者简单地说,
children[from]?.append(to)
推荐阅读
- python - 如何使用 argparse 获取带有标志参数的输入作为字符串
- javascript - Cloudflare SSL Err 522 Express
- php - 在准备好的语句中找不到问题的解决方案(程序 php)
- angular - Angular 无法解析 SomeEffect 的所有参数(?)
- html - 在 IE 的下拉菜单后面时,输入字段中的文本光标仍然可见
- python - 使用 mixin 时返回基类的签名
- javascript - 刷新 select2 下拉列表
- google-apps-script - Apps 脚本插件 onOpen(e) 是否显示菜单或发送电子邮件
- react-native - 在标题中使用按钮进行反应导航
- java - 如何将数据从一个活动显示到另一个活动并同时保存?