我正在使用此代码从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!)
}
但是当我items
或nextPageToken
不存在时,我会收到此错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
知道为什么吗?我怎么能解决它?
答案 0 :(得分:5)
您的代码中存在两个问题:
valueForKey:
而不是objectForKey:
来检索词典中的数据。使用objectForKey: instead of valueForKey:从字典中获取数据。您可以通过以下方式修复崩溃:
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!)
}
}
}