首页 > 解决方案 > 如何从字典内的数组中检索项目?

问题描述

我正在尝试创建一个字典,其中包含一个数组作为 Swift 中字典项之一的值。我希望能够检索数组中的某个元素,但是当我尝试这样做时出现错误。

这是我的代码:

var country = ["USA": [37.0902, 95.7129]]

let countrylatitude = country["USA"]
print(countrylatitude[0])

错误消息是:可选类型“[Double]?”的值 必须展开以引用已封装基类型“[Double]”的成员“下标”

这是什么意思?谢谢!

标签: arraysswiftxcodedictionary

解决方案


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]


推荐阅读