swift - 仅当键在字典中可用时才获取数据

标签 swift xcode dictionary key

我有以下类型的字典:

{
  "filter": {
    "year_option": {
      "2015": "2015",
      "2016": "2016"
    },
    "month_option": {
      "10": "Oct",
      "11": "Nov",
      "12": "Dec",
      "01": "Jan",
      "02": "Feb",
      "03": "Mar",
      "04": "Apr",
      "05": "May",
      "06": "Jun",
      "07": "Jul",
      "08": "Aug",
      "09": "Sept"
    }
  }
}

这是来自 API 的响应。 字典中的键可能因每个用户而异。那么有没有办法仅在键可用时获取Dictionary值?

最佳答案

当然,有办法。使用 if let 检查是否存在 key 。 例如:

if let key1 = yourDict["key1"] {
   // do something with key1
}

使用您的示例:

if let filter = yourDict["filter"] as? [String: Any] {
   if let yearOption = filter["year_option"] as? [String: String] {
      // there is the year_option JSON
   }
   if let monthOption = filter["month_option"] as? [String:String] {
      // there is the month option JSON
   }
}

关于swift - 仅当键在字典中可用时才获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41118418/

相关文章:

swift - 从多重选择器行检索值时出现问题

ios - 检测 IOS 10(Swift 3、Xcode 8)中的 GSM 调用状态和来自后台状态的通知

xcode - 在钥匙串(keychain)中找不到有效的 iOS 代码签名 key 。您需要申请一个代码签名证书

ios - 识别标签中显示的属性字符串中的图像点击

python - 有效地反转和反转 python3.x OrderedDict

arrays - 如何在 swift 中创建一个 SCNNode 数组

xcode - UIButton Swift 上的多行标签

ios - Swift 2.1 - 自定义 UITableViewCell 类中的 IBOutlet 属性为 nil

python - 我如何在Python中将嵌套列表作为字典值进行迭代和排序?

Python - collections.OrderedDict() 未正确排序字典