ios Swift 从 NSDictionary 读取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33367183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:06:39  来源:igfitidea点击:

Swift read data from NSDictionary

iosiphonejsonswiftnsdictionary

提问by MTA

I am using this code to read data from NSDictionary:

我正在使用此代码从NSDictionary以下位置读取数据:

let itemsArray: NSArray = response.objectForKey("items") as! NSArray;
let nextPageToken: String = response.objectForKey("nextPageToken") as! String

var videoIdArray: [String] = []

for (item) in itemsArray {
      let videoId: String? = item.valueForKey("id")!.valueForKey("videoId") as? String
      videoIdArray.append(videoId!)
}

But when i itemsor nextPageTokenare not exist i get this error:

但是当我itemsnextPageToken不存在时,我会收到此错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

Any idea why? how i can fix it?

知道为什么吗?我该如何解决?

回答by Midhun MP

There are two issues in your code:

您的代码中有两个问题:

  1. You are trying to force unwrap an optional that can be nil. Never use forced unwrapping, if you are not sure whether the data will be available or not.
  2. You are using valueForKey:instead of objectForKey:for retrieving data from a dictionary. Use objectForKey: instead of valueForKey:for getting data from a dictionary.
  1. 您正在尝试强制解开一个可以为零的可选项。如果您不确定数据是否可用,切勿使用强制解包。
  2. 您正在使用valueForKey:而不是objectForKey:从字典中检索数据。使用objectForKey: 而不是 valueForKey:从字典中获取数据。

You can fix the crash by:

您可以通过以下方式修复崩溃:

let itemsArray: NSArray?   = response.objectForKey("items") as? NSArray;
let nextPageToken: String? = response.objectForKey("nextPageToken") as? String

var videoIdArray: [String] = []
if let itemsArray = itemsArray
{
    for (item) in itemsArray
    {
       let videoId: String? = item.objectForKey("id")?.objectForKey("videoId") as? String
       if (videoId != nil)
       {
          videoIdArray.append(videoId!)
       }
     }
}