arrays - 如何从字典内的数组中检索项目?
问题描述
我正在尝试创建一个字典,其中包含一个数组作为 Swift 中字典项之一的值。我希望能够检索数组中的某个元素,但是当我尝试这样做时出现错误。
这是我的代码:
var country = ["USA": [37.0902, 95.7129]]
let countrylatitude = country["USA"]
print(countrylatitude[0])
错误消息是:可选类型“[Double]?”的值 必须展开以引用已封装基类型“[Double]”的成员“下标”
这是什么意思?谢谢!
解决方案
Unwrapped 基本上意味着检查并确保该值存在。countrylatitude 可能等于 nil,因为它不知道“USA”是否是字典的一部分。
有多种方法可以打开以确保它存在......
如果它等于 nil,force unwrap 会崩溃
countrylatitude![0]
if let 仅在它可以定义不等于 nil 的常量时运行
if let latitude = countrylatitude {
print(latitude[0])
}
guard let 不会在 guard 语句之后运行任何代码,除非它不等于 nil
guard let latitude = countrylatitude else { return }
print(latitude[0])
请记住,如果 latitude[0] 的索引不是自动分配的,那么如果你这样做,它本质上只是强制解开索引,如果该索引不存在countrylatitude[0]
,它将崩溃。[0]
推荐阅读
- html - 在 Ionic 3 中动态改变 CSS 值
- node.js - 你可以在共享驱动器上运行 Node.js 吗?
- git - TortoiseGit 图标覆盖在未修改时显示已修改
- node.js - util.promisify node js的正确使用
- python - Python:一次多次 Ping URL 以进行测试
- python - 如何使用python解析xml后创建csv文件
- angular - 出现输入框,但点击后什么也没有
- javascript - 跨 Karma 单元测试和 Protractor 端到端测试共享的测试库
- excel - 条件格式 - if 和语句
- php - 我在这个文件中有 index.php 当我尝试用 css 设置样式时有 html 没有影响