簡體   English   中英

如何訪問 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] for hoursDictionary,但這對我不起作用。

我不斷收到的錯誤是在 if 語句行:if Int(hoursDictionary[0][5][2]) > Integer for a certain time {, and the error text is: “Value of type 'Any?' 沒有下標”。 我知道這是因為我試圖訪問的 NSDictionary 的鍵值具有 Any 類型的值。

我認為錯誤出在這個 if 語句中的某個地方,並且與更改字典中我試圖訪問 Int 的那部分的數據類型有關。

我使用的 API 是 Yelp Fusion API,我使用的 API 搜索是“商家詳情”。 這是此文檔的鏈接: 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`.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM