Swift read data from NSDictionary

不打扰是莪最后的温柔 提交于 2019-12-12 15:41:15

问题


I am using this code to read data from 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 items or nextPageToken are not exist i get this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Any idea why? how i can fix it?


回答1:


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.

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!)
       }
     }
}


来源:https://stackoverflow.com/questions/33367183/swift-read-data-from-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!