如何访问 NSDictionary 的索引,并将该键的值转换为 Swift 中的 Int?

How to access indices of an NSDictionary, and convert that key’s value to an Int in Swift?

我正在尝试访问 NSDictionary 的索引,并使用 Swift 将该键的值转换为 Int。

我也在使用 API 来获取数据。 API 响应是我用来创建初始字典的内容,然后我从 API 响应的“小时”部分创建字典。我的代码的 API 调用部分可以正常工作,所以我只包含了与访问 hoursDictionary 相关的代码。

在网上查找这个问题后,我尝试使用 [[[String: Any]]] 而不是 [NSDictionary] 来使用 hoursDictionary,但这对我不起作用。

我不断收到的错误是在 if 语句行:if Int(hoursDictionary[0][5][2]) > Integer for a certain time { ,错误文本是:“Value of type 'Any?'没有下标”。我知道这是因为我试图访问的 NSDictionary 的键值具有 Any 类型的值。

我认为错误出在这个 if 语句中的某个地方,并且与更改字典中我试图访问 Int 的那部分的数据类型有关。

我使用的 API 是 Yelp Fusion API,我使用的 API 搜索是“业务详情”。这是此文档的 link:https://www.yelp.com/developers/documentation/v3/business .

返回的 API 响应正文示例以及我正在访问的内容如下:

{
  "id": "WavvLdfdP6g8aZTtbBQHTw",
  "alias": "gary-danko-san-francisco",
  "name": "Gary Danko",
  "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/CPc91bGzKBe95aM5edjhhQ/o.jpg",
  "is_claimed": true,
  "is_closed": false,
  "url": "https://www.yelp.com/biz/gary-danko-san-francisco?adjust_creative=wpr6gw4FnptTrk1CeT8POg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_lookup&utm_source=wpr6gw4FnptTrk1CeT8POg",
  "phone": "+14157492060",
  "display_phone": "(415) 749-2060",
  "review_count": 5296,
  "categories": [
    {
      "alias": "newamerican",
      "title": "American (New)"
    },
    {
      "alias": "french",
      "title": "French"
    },
    {
      "alias": "wine_bars",
      "title": "Wine Bars"
    }
  ],
  "rating": 4.5,
  "location": {
    "address1": "800 N Point St",
    "address2": "",
    "address3": "",
    "city": "San Francisco",
    "zip_code": "94109",
    "country": "US",
    "state": "CA",
    "display_address": [
      "800 N Point St",
      "San Francisco, CA 94109"
    ],
    "cross_streets": ""
  },
  "coordinates": {
    "latitude": 37.80587,
    "longitude": -122.42058
  },
  "photos": [
    "https://s3-media2.fl.yelpcdn.com/bphoto/CPc91bGzKBe95aM5edjhhQ/o.jpg",
    "https://s3-media4.fl.yelpcdn.com/bphoto/FmXn6cYO1Mm03UNO5cbOqw/o.jpg",
    "https://s3-media4.fl.yelpcdn.com/bphoto/HZVDyYaghwPl2kVbvHuHjA/o.jpg"
  ],
  "price": "$$$$",
  "hours": [
    {
      "open": [
        {
          "is_overnight": false,
          "start": "1730",
          "end": "2200",
          "day": 0
        },
        {
          "is_overnight": false,
          "start": "1730",
          "end": "2200",
          "day": 1
        },
        {
          "is_overnight": false,
          "start": "1730",
          "end": "2200",
          "day": 2
        },
        {
          "is_overnight": false,
          "start": "1730",
          "end": "2200",
          "day": 3
        },
        {
          "is_overnight": false,
          "start": "1730",
          "end": "2200",
          "day": 4
        },
        {
          "is_overnight": false,
          "start": "1730",
          "end": "2200",
          "day": 5
        },
        {
          "is_overnight": false,
          "start": "1730",
          "end": "2200",
          "day": 6
        }
      ],
      "hours_type": "REGULAR",
      "is_open_now": false
    }
  ],
  "transactions": [],
  "special_hours": [
    {
      "date": "2019-02-07",
      "is_closed": null,
      "start": "1600",
      "end": "2000",
      "is_overnight": false
    }
  ]
}

我的代码片段:

FetchData.swift

                        /// Read data as JSON
                        let json = try JSONSerialization.jsonObject(with: data!, options: [])
                        
                        /// Main dictionary
                        guard let responseDictionary = json as? NSDictionary else {return}
                        
                        /// Creating hours dictionary,
                        guard let hoursDictionary = responseDictionary.value(forKey: "hours") as? [NSDictionary] else {return}
                        
                        if let endTimeAsString = hoursDictionary["open"][5]["end"] as? String,
                        let endTimeAsInt = Int(endTimeAsString),
                        endTimeAsInt > An integer representing a certain time {

                          // Do something
                            
}                   

您不能像访问数组那样访问字典的第 [nth] 个索引,因为字典是一个 无序 集合。相反,您必须执行类似 [CORRECTED] hoursDictionary[0]["open"][5]["end"] 或任何顺序的操作才能获得所需的值。

或者,我倾向于将其拆分,这样我可以确保正确处理每个步骤,如下所示:

guard let hoursDictionaries = responseDictionary.value(forKey: "hours") as? [NSDictionary] else {return}
                        
if let firstHoursDictionary = hoursDictionaries[0] as? NSDictionary,
   let openDictionarys = firstHoursDictionary["open"] as? [NSDictionary],
   let firstOpenDictionary = openDictionarys[5] as? NSDictionary,
   let endTimeAsString = firstOpenDictionary["end"] as? String,
   let endTimeAsInt = Int(endTimeAsString),
   endTimeAsInt > someInt {

    // Do something
}

// Remember, you can always check what type the compiler is inferring something 
// to be by right-clicking on the variable name and clicking `Show Quick Help`.