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

发布于 2025-01-16 17:16:09 字数 4285 浏览 0 评论 0原文

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

我还使用 API 来获取数据。我使用 API 响应来创建初始字典,然后根据 API 响应的“小时”部分创建字典。我的代码的 API 调用部分正在运行,因此我只包含与访问 hoursDictionary 相关的代码。

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

我不断收到的错误位于 if 语句行: if Int(hoursDictionary[0][5][2]) >某个时间的整数 { ,错误文本为:“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
                            
}                   

I’m trying to access indices of an NSDictionary, and convert that key’s value to an Int using Swift.

I’m also using an API to fetch data. The API response is what I’m using to create an initial dictionary out of, then I create a dictionary out of the “hours” part of the API response. The API call part of my code is working, so I’ve only included code related to accessing the hoursDictionary.

I’ve tried using [[[String: Any]]] instead of [NSDictionary] for hoursDictionary after looking up this problem online, but this did not work for me.

The error I keep getting is at the if statement line: if Int(hoursDictionary[0][5][2]) > Integer for a certain time { , and the error text is: “Value of type 'Any?' has no subscripts”. I know this is because the NSDictionary’s key’s value that I’m trying to access has a value of type Any.

I think the error is somewhere in this if statement, and is related to changing the data type of that part in the dictionary that I’m trying to access to an Int.

The API that I’m using is the Yelp Fusion API, and the API search that I’m using is “Business Details”. Here’s a link to this documentation: https://www.yelp.com/developers/documentation/v3/business .

An example of the API response body that is being returned and what I’m accessing is the following:

{
  "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
    }
  ]
}

Snippet of my code:

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
                            
}                   

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余厌 2025-01-23 17:16:09

您无法像访问数组一样访问字典的 [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`.

You can't access a dictionary's [nth] index like you would an array because a dictionary is an unordered collection. Instead you would have to do something like this [CORRECTED] hoursDictionary[0]["open"][5]["end"], or whatever sequence to get the value you need.

Or, I tend to split this up so I can ensure I am processing each step correctly like so:

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`.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文