我有一个使用Foursquare API下载JSON数据的应用程序。我使用NSURLSession
和dataTaskWithRequest
以完成块方法来获取数据。我得到的数据很好,但有时一个名为groups
的嵌套数组可能是空的。而当我通过下面的JSON解析时,出于某种原因,我的条件语句没有像我期待的那样处理空数组。相反,阵列评价为空,在进行if let...else
语句的“其他”部分,如果不是得来运行时错误陈述的:index 0 beyond bounds of empty array
Swift:如果let语句无法处理空数组
if let response: NSDictionary = data["response"] as? [String: AnyObject],
groups: NSArray = response["groups"] as? NSArray,
// Error here \|/ (sometimes groups array is empty)
dic: NSDictionary = groups[0] as? NSDictionary,
items: NSArray = dic["items"] as! NSArray {
}
else {
// Never gets here. Why?
// IF the groups array is empty, then the if let should return
// false and drop down to the else block, right?
}
我是比较新的雨燕,谁能告诉我这是为什么发生的以及我能做些什么来解决这个问题?由于
你尝试nsnull检查阵列响应对象的值? – Loxx
意思是实际测试类类型NSNull? – Loxx
我知道我可以这样做,我只是想在这里理解Swift。在我看来,如果它是空的(意思是错误的),它会这样评价。而且,如果语句通常会这样做,他们就会下降到else块。我想如果让Swift的话,我会有点困惑。 –